How to parse xml using jaxb

I'm new to JAXB, I want to read an XML file for a 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.

+2


source to share


2 answers


This is your script

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 of 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>

      

+2


source


For this use case, you will have one class with a property List<String>

. Only the annotations, you may need are @XmlRootElement

and @XmlElement

to map the properties of List

an element payType

.

Additional Information



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

+1


source







All Articles