2

I am new in JAXB, I want to read XML file to Java object, which is in the following format:

<payTypeList> 
    <payType>G</payType> 
    <payType>H</payType> 
    <payType>Y</payType> 
 </payTypeList>

Please help me how to read this type of XML.

jny
  • 8,007
  • 3
  • 37
  • 56
Arvind Singh
  • 75
  • 2
  • 6

2 Answers2

2

This is your scenario

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="payTypeList")
@XmlAccessorType(XmlAccessType.FIELD)
public class PayTypeList {

    @XmlElement
    private List<String> payType;

    public List<String> getPayType() {
        return payType;
    }

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

Method to use

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

            final 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);
        }

Output.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<payTypeList>
    <payType>one</payType>
    <payType>two</payType>
    <payType>three</payType>
</payTypeList>
Xstian
  • 8,184
  • 10
  • 42
  • 72
1

For this use case you will have a single class with a List<String> property. The only annotations you may need to use are @XmlRootElement and @XmlElement to map the List property to the payType element.

For More Information

You can find more information about using these annotations on my blog:

bdoughan
  • 147,609
  • 23
  • 300
  • 400