Arvind Singh
Arvind Singh

Reputation: 75

How parse xml using jaxb

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.

Upvotes: 2

Views: 194

Answers (2)

Xstian
Xstian

Reputation: 8282

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>

Upvotes: 2

bdoughan
bdoughan

Reputation: 149047

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:

Upvotes: 1

Related Questions