Java 使用JAXB仅将最后一个元素写入XML
我想将来自数据库的数据写入xml文件。共有5个数据。问题是JAXB只将最后一个数据写入xml文件Java 使用JAXB仅将最后一个元素写入XML,java,xml,jaxb,Java,Xml,Jaxb,我想将来自数据库的数据写入xml文件。共有5个数据。问题是JAXB只将最后一个数据写入xml文件 public void createXmlFile() { String path = Labels.getLabel("zk.file.xmlfilepath"); Kitap k = new Kitap(); File xmlFile = new File(path); try { if (xmlFile.createNewFile()) {
public void createXmlFile() {
String path = Labels.getLabel("zk.file.xmlfilepath");
Kitap k = new Kitap();
File xmlFile = new File(path);
try {
if (xmlFile.createNewFile()) {
System.out.println("Kitaplar.xml file created.");
} else {
System.err.println("Kitaplar.xml file can't created!");
}
JAXBContext jaxbContext = JAXBContext.newInstance(Kitap.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
for (int i = 0; i < kitapList.size(); i++) {
k.setKitapId(kitapList.get(i).getKitapId());
k.setKitapad(kitapList.get(i).getKitapad());
k.setYazarad(kitapList.get(i).getYazarad());
k.setKitapdurum(kitapList.get(i).getKitapdurum());
k.setKitaptur(kitapList.get(i).getKitaptur());
k.setKitapImage(kitapList.get(i).getKitapimage());
jaxbMarshaller.marshal(k, xmlFile);
jaxbMarshaller.marshal(k, System.out);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
我的代码出了什么问题?为什么只有最后一个元素写入xml文件?请阅读JAXB封送器的规范: 更重要的是:
File to be written. If this file already exists, it will be overwritten.
您正在循环内部编组,因此基本上每次都会用最后一个元素覆盖文件
一个解决方案是制作一个包装对象,它有一个列表:<代码> Kitap < /Cord>对象和编组包装对象。可能文件总是被覆盖…或者您序列化到
FileOutputStream
或FileWriter
并在调用marshal
(虽然输出将不是有效的XML作为@ErwinBolwidt,但它也将无效,因为它将有多个根标记。我不理解解决方案。是否有任何代码示例?
File to be written. If this file already exists, it will be overwritten.