问题在于每次执行main方法时,a.xml的旧内容都会丢失并被替换为新内容。如何将内容附加到a.xml文件而不丢失以前的信息?
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;
}
}
答案 0 :(得分:3)
问题是,您确实要将序列化的XML字符串附加到文件中,还是要将新的Foo实例添加到XML结构中。
以字符串为基础附加会导致XML无效,如下所示:
<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>
相反,您可能希望先通过解析来保存a.xml中的数据,然后添加新元素并序列化整个集合/数组。
这样的事情(假设a.xml中已经有Foo
的集合):
List foos = xs.fromXml(...);
foos.add(new Foo(1, "booo", new Bar(42)));
xs.toXml(foos, pw);
...它为您提供了以下内容:
<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
答案 1 :(得分:2)
示例代码
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);
}