如何使用jaxb解析xml [英] How parse xml using jaxb

查看:92
本文介绍了如何使用jaxb解析xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JAXB的新手,我想将XML文件读取为Java对象,其格式如下:

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>

请帮助我阅读这种XML.

Please help me how to read this type of XML.

推荐答案

这是您的情况

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

使用方法

       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>

这篇关于如何使用jaxb解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆