XStream

 

一、简单例子

  简单的说明一下XStream的用法,此例是把Person和PhoneNumber两个之间有关系的类解析成一个XML。这个例子需要xstream-1.3.1.jar和xpp3_min-1.1.4c.jar两个包。

public class Person {
    private String firstName;
    private String lastName;
    private PhoneNumber phone;
    private PhoneNumber fax;
   
    public Person(String firstName, String lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
    }  
    // Getter and Setter
}

public class PhoneNumber {
    private int code;
    private String number;
   
    public PhoneNumber(int code, String number) {
        this.code = code;
        this.number = number;
    }
    // Getter and Setter
}

public class Test {

    public static void main(String[] args) {
      
       // XStream默认的构造函数是调用XPP3来解析XML的,
       // XPP3是一个pull-parser实现,据说这是目前最快的解析XML的类
      
       // 我们也可以不用这个,还用JAXP去解析
       // XStream xstream = new XStream(new DomDriver());
      
       XStream xstream = new XStream();
      
       // 为类设置别名
       // 如果不设置,生成的XML会是类的全称,含包名
       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"));
      
       // 解析Object成XML
       String xml = xstream.toXML(joe);      
      
       // 把XML解析成Object
       Person newJoe = (Person)xstream.fromXML(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> 

从这个例子可以看到,有了XStream这个工具例,Object转换成XML,或把XML转换成Object是多么的简单。

 

二、XStream结合XSL

XStream xstream = new XStream();
xstream.alias("person", Person.class);

File file = new File("test\\appAuditAllRequest.xsl");
TraxSource traxSource = new TraxSource(new Person("Joe", "Walnes"), xstream);
Writer buffer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer(
    new StreamSource(file));
transformer.transform(traxSource, new StreamResult(buffer));
 

 

你可能感兴趣的:(xstream)