Java HTML / XML How to - Output List item using jaxb








Question

We would like to know how to output List item using jaxb.

Answer

import java.util.ArrayList;
import java.util.List;
//from   w w w. j av  a  2s  .  co  m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {
  public static void main(String[] args) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(PayTypeList.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    PayTypeList paymentType = new PayTypeList();

    List<String> paymentTypes = new ArrayList<String>();
    paymentTypes.add("one");
    paymentTypes.add("two");
    paymentTypes.add("three");
    paymentType.setPayType(paymentTypes);

    m.marshal(paymentType, System.out);
  }
  @XmlRootElement(name = "payTypeList")
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class PayTypeList {

    @XmlElement
    private List<String> payType;

    public List<String> getPayType() {
      return payType;
    }
    public void setPayType(List<String> payType) {
      this.payType = payType;
    }
  }
}