问题描述
我有以下 xml 格式,我想通过 POJO 并使用 JAXB 注释来绑定它.XML 格式如下:
I have the following xml format that i want to bind it through a POJO and using JAXB annotations. The XML format is the following:
<datas> <data>apple<data> <data>banana<data> <data>orange<data> <datas>
我正在尝试通过以下 POJO 绑定数据:
And i'm trying to bind the data through the following POJO:
@XmlRootElement() @XmlAccessorType(XmlAccessType.FIELD) public class Datas { @XmlElement private List<String> data; //get/set methods }
我也尝试过这个 POJO:
And also i try and this POJO:
@XmlRootElement() @XmlAccessorType(XmlAccessType.FIELD) public class Datas { @XmlElement private List<Data> datas; //get/set methods }
//
@XmlRootElement() @XmlAccessorType(XmlAccessType.FIELD) public class Data{ @XmlElement private String data; //get/set methods }
在第一种情况下,它只检索第一个数据:apple.在第二种情况下不检索任何东西.有人可以帮我提供适当的 POJO 和注释以绑定所有数据吗?
In the first case it retrieves only the first data: apple. In the second case doesn't retrieve anything. Could someone help me to provide the appropriate POJO and annotations in order to bind all data?
推荐答案
您可以执行以下选项之一:
You can do one of the following options:
选项 #1
数据
package forum11311374; import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Datas { private List<String> data; //get/set methods }
更多信息
- http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
选项 #2
数据
package forum11311374; import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Datas { @XmlElement(name="data") private List<Data> datas; //get/set methods }
数据
package forum11311374; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Data{ @XmlValue private String data; //get/set methods }
更多信息
- http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html
以下两个选项都可以使用:
The following can be used with both options:
input.xml/输出
我已更新 XML 文档以包含必要的结束标记.<data>apple</data> 而不是 <data>apple
I have updated the XML document to contain the necessary closing tags. <data>apple</data> instead of <data>apple<data>.
<datas> <data>apple</data> <data>banana</data> <data>orange</data> </datas>
演示
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); } }