XStream小热身

XStream is a simple library to serialize objects to XML and back again.

XStream就是一个对象和XML之间的映射工具。

例1. Object > XML

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
}
XStream xstream = new XStream();
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
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);
System.out.println(xml);

输出结果:

<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>

例2. XML > Object

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

Leave a Comment.