Serializing Java objects to XML with XStream

爷,独闯天下 提交于 2019-11-30 18:04:14

问题


The problem is that every time I execute the main method, the old content of a.xml is lost and is substituted with a new one. How to append content to the a.xml file without losing the previous information?

import java.io.FileNotFoundException;
import java.io.PrintWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


public class Test {
    public static void main(String[] args) throws FileNotFoundException {
        XStream xs = new XStream(new DomDriver());
        Foo f = new Foo(1, "booo", new Bar(42));
        PrintWriter pw = new PrintWriter("a.xml");
        xs.toXML(f,pw);
    }
}


public class Bar {
    public int id;

    public Bar(int id) {
        this.id = id;
    }

}


public class Foo {
    public int a;
    public String b;
    public Bar boo;
    public Foo(int a, String b, Bar c) {
        this.a = a;
        this.b = b;
        this.boo = c;
    }
}

回答1:


Sample Code

public static void main(String a[]){
  //Other code omitted
  FileOutputStream fos = new FileOutputStream("c:\\yourfile",true); //true specifies append
  Foo f = new Foo(1, "booo", new Bar(42));
  xs.toXML(f,fos);
}



回答2:


The question is, do you really want to append the serialized XML string to the file or do you want to add the new Foo instance to the XML structure.

Appending on a string basis would result in invalid XML about like this:

<foo>
  <a>1</a>
  <b>booo</b>
  <bar>
    <id>42</id>
  </bar>
</foo>
<foo>
  <a>1</a>
  <b>booo</b>
  <bar>
    <id>42</id>
  </bar>
</foo>

Instead you may want to preserve the data in a.xml by parsing it first, then add the new element and serialize the whole collection/array.

So something like this (assuming there is already a collection of Foos in a.xml):

List foos = xs.fromXml(...);
foos.add(new Foo(1, "booo", new Bar(42)));
xs.toXml(foos, pw);

... which gives you something along the lines of this:

<foos>
  <foo>
    <a>1</a>
    <b>booo</b>
    <bar>
      <id>42</id>
    </bar>
  </foo>
  <foo>
    <a>1</a>
    <b>booo</b>
    <bar>
      <id>42</id>
    </bar>
  </foo>
</foos>

HTH



来源:https://stackoverflow.com/questions/3143234/serializing-java-objects-to-xml-with-xstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!