我是 JAXB 新手,我想将 XML 文件读取为 Java 对象,其格式如下:
<payTypeList>
<payType>G</payType>
<payType>H</payType>
<payType>Y</payType>
</payTypeList>
请帮助我如何读取这种类型的 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);
}
输出.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<payTypeList>
<payType>one</payType>
<payType>two</payType>
<payType>three</payType>
</payTypeList>
关于java - 如何使用jaxb解析xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25265834/