假设我想用XML存储许多小的配置对象,并且我不太关心格式。这XML解码器 http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLDecoder.htmlJDK 中内置的类可以工作,据我所知,XStream http://xstream.codehaus.org/以类似的方式工作。
每个图书馆有什么优势?
我真的很喜欢XStream http://xstream.codehaus.org/图书馆。它在输出相当简单的 xml 方面做得非常好
作为提供的 Java 对象的结果。它非常适合繁殖
对象也从 xml 返回。并且,我们的第三方库之一
反正已经依赖它了。
两分钟的教程总结了基本用法,但在
有兴趣将信息保留在一个地方,我会尝试总结它
到这里,稍微短一点。
// define your classes
public class Person {
private String firstname;
private PhoneNumber phone;
// ... constructors and methods
}
public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}
然后使用该库写出 xml。
// initial the libray
XStream xstream = new XStream();
xstream.alias("person", Person.class); // elementName, Class
xstream.alias("phone", PhoneNumber.class);
// make your objects
Person joe = new Person("Joe");
joe.setPhone(new PhoneNumber(123, "1234-456"));
// convert xml
String xml = xstream.toXML(joe);
您的输出将如下所示:
<person>
<firstname>Joe</firstname>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
</person>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)