Serializing Java objects to XML with XStream

痴心易碎 提交于 2019-11-30 22:53:47

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

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

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