使用POJO和JAXB注释绑定XML

我有以下xml格式,我想通过POJO和使用JAXB注释绑定它。 XML格式如下:

 apple banana orange  

我正在尝试通过以下POJO绑定数据:

 @XmlRootElement() @XmlAccessorType(XmlAccessType.FIELD) public class Datas { @XmlElement private List data; //get/set methods } 

而且我也试着这个POJO:

 @XmlRootElement() @XmlAccessorType(XmlAccessType.FIELD) public class Datas { @XmlElement private List datas; //get/set methods } 

//

 @XmlRootElement() @XmlAccessorType(XmlAccessType.FIELD) public class Data{ @XmlElement private String data; //get/set methods } 

在第一种情况下,它只检索第一个数据:apple。 在第二种情况下不检索任何东西。 有人可以帮我提供适当的POJO和注释以绑定所有数据吗?

您可以执行以下选项之一:

选项1

DATAS

 package forum11311374; import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Datas { private List data; //get/set methods } 

了解更多信息


选项#2

DATAS

 package forum11311374; import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Datas { @XmlElement(name="data") private List datas; //get/set methods } 

数据

 package forum11311374; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Data{ @XmlValue private String data; //get/set methods } 

了解更多信息


以下两个选项均可使用:

input.xml中/输出继电器

我已更新XML文档以包含必要的结束标记。 apple而不是apple

  apple banana orange  

演示

 package forum11311374; import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Datas.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum11311374/input.xml"); Datas datas = (Datas) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(datas, System.out); } } 

第一个选项对我有用…不确定为什么你会遇到问题…尝试这个注释…

 @XmlElements(@XmlElement(name="data", type=String.class)) private List datas; //ignore the variable name