XStream 快速转换xml

时间:2023-12-10 10:44:44

项目地址:http://xstream.codehaus.org/tutorial.html

(以下来源于官网)

1、Create classes to be serialized(初始化类)

public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
} public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}

2、Initializing XStream(初始化XStream)

XStream xstream = new XStream();
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);

3、Serializing an object to XML(转换为xml例子)

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
<person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
</person>

4、Deserializing an object back from XML(xml逆转)

Person newJoe = (Person)xstream.fromXML(xml);