也许一个愚蠢的问题:我有一个类型< Data>我想要封送到一个XML文件。这是我的类数据库包含一个ArrayList …
@XmlRootElement public class Database { List<Data> records = new ArrayList<Data>(); public List<Data> getRecords() { return records; } public void setRecords(List<Data> records) { this.records = records; } }
…这是类Data:
// @XmlRootElement public class Data { String name; String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
使用以下测试类…
public class Test { public static void main(String args[]) throws Exception { Data data1 = new Data(); data1.setName("Peter"); data1.setAddress("Cologne"); Data data2 = new Data(); data2.setName("Mary"); data2.setAddress("Hamburg"); Database database = new Database(); database.getRecords().add(data1); database.getRecords().add(data2); JAXBContext context = JAXBContext.newInstance(Database.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); marshaller.marshal(database,new FileWriter("test.xml")); } }
…我得到的结果:
<database> <records> <address>Cologne</address> <name>Peter</name> </records> <records> <address>Hamburg</address> <name>Mary</name> </records> </database>
但这不是我的期望,即所有标签< Data>对象丢失。我正在寻找一种方式导出数据在以下结构,但我不知道如何实现这一点:
<database> <records> <data> <address>Cologne</address> <name>Peter</name> </data> <data> <address>Hamburg</address> <name>Mary</name> </data> </records> </database>
另外一个问题:如果我想处理这个问题,而不使用@XmlElementWrapper和@XmlElement注释,我可以引入一个中间类
public class Records { List<Data> data = new ArrayList<Data>(); public List<Data> getData() { return data; } public void setData(List<Data> data) { this.data = data; } }
由修改的基类使用
@XmlRootElement public class Database { Records records = new Records(); public Records getRecords() { return records; } public void setRecords(Records records) { this.records = records; } }
在稍微修改一下测试类:
... Database database = new Database(); database.getRecords().getData().add(data1); database.getRecords().getData().add(data2); ...
结果也是:
<database> <records> <data> <address>Cologne</address> <name>Peter</name> </data> <data> <address>Hamburg</address> <name>Mary</name> </data> </records> </database>