开发者

Serializing Java objects to XML with XStream

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;
    publi开发者_开发知识库c Foo(int a, String b, Bar c) {
        this.a = a;
        this.b = b;
        this.boo = c;
    }
}


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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜