![](/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.