![](/img/trans.png)
[英]How to add wrapper while converting JSON array object into XML in Java
[英]How to add an object to xml in Java?
我創建了XML文件作為我創建的對象(稱為“三重”)的數據庫。 當我嘗試添加新對象(相同類型)的另一行時,它將刪除前一行。 如何添加而不刪除? (在前一行下)
這是代碼:
public class RDB {
File file;
String filepath;
JAXBContext jaxbContext;
Marshaller jaxbMarshaller;
RDB(){
filepath = "RDB.xml";
file = new File(filepath);
StreamResult result = new StreamResult(file);
try {
jaxbContext = JAXBContext.newInstance(triple.class);
jaxbMarshaller = jaxbContext.createMarshaller();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void addToXml(triple t){
try {
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(t, file);
jaxbMarshaller.marshal(t, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
public static void main(String argv[]) {
RDB r = new RDB();
r.addToXml(new triple(1,2,3));
r.addToXml(new triple(4,5,6));
}
三重類如下所示:
public class triple implements Serializable {
private static final long serialVersionUID = 1L;
private double x, y;
private int z;
triple(double x , double y, int z){
this.x = x;
this.y = y;
this.z = z;
}
謝謝!
您每次都編組一個對象。 您在每次調用addToXml()時都會覆蓋該文件。
請嘗試實現一個具有“ triple”數組的類,然后封送該類。
使用FileOutputStream以附加模式寫入xml,例如:
OutputStream out = FileOutputStream( file, true);
然后使用jaxbMarshaller.marshal( t, out );
完成后,請確保正確關閉流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.