How parse xml using jaxb

廉价感情. 提交于 2019-12-11 01:57:27

问题


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.


回答1:


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>



回答2:


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:

  • http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html
  • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html


来源:https://stackoverflow.com/questions/25265834/how-parse-xml-using-jaxb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!