在以前的xml处理中,本人一直使用dom或者sax,首先解析xml文档,然后把解析出来的数据填入到一个对象中,最后在程序中使用这个对象。程序员就是懒,最近在网上看到了可以直接把XML和Java对象互相转换的工具,觉得非常棒,以下是一个简单的例子。
这种方式叫做xStream,它并不是一种新的解析形式,只是把以前的解析,填装两步封装在一起,让我们觉得更加好用而已,解析的支持默认的是xpp3,当然你也可以使用dom或者其他的,无关紧要。在开始例子之前,需要下载两个支持包:xpp3.jar和xstream-1.4.1.jar,地址分别是:http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadxpp3jar.htm和http://xstream.codehaus.org/download.html
代码:
1.两个辅助类(JavaBean):
package app.xstream; public class Person { private String firstName; private String lastName; private PhoneNumber phonex; private PhoneNumber fax; public Person(String firstName, String lastName, PhoneNumber phonex, PhoneNumber fax) { this.firstName = firstName; this.lastName = lastName; this.phonex = phonex; this.fax = fax; } public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public PhoneNumber getPhonex() { return phonex; } public void setPhonex(PhoneNumber phonex) { this.phonex = phonex; } public PhoneNumber getFax() { return fax; } public void setFax(PhoneNumber fax) { this.fax = fax; } }
package app.xstream; public class PhoneNumber { private int code; private int number; public PhoneNumber(int code, int number) { super(); this.code = code; this.number = number; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } }
2.测试类:
package app.xstream; import com.thoughtworks.xstream.XStream; /** * * @author 冯小卫 * */ public class Main { public static void main(String[] args) { // XStream可以完成XML和普通的Java对象之间的转换 XStream xStream = new XStream(); // 构建Java对象和XML中结构体的联系 xStream.alias("person", Person.class); Person joe = new Person("Joe", "Walnes"); joe.setPhonex(new PhoneNumber(123, 456)); joe.setFax(new PhoneNumber(123, 110)); // 把Java对象转化为XML文件 String xml = xStream.toXML(joe); System.out.println(xml); System.out.println("------------------------------------------"); // 把XML文件解析为Java对象 Person newJoe = (Person) xStream.fromXML(xml); System.out.println(newJoe.getFirstName() + " " + newJoe.getLastName() + " " + newJoe.getPhonex().getCode() + " " + newJoe.getPhonex().getNumber() + " " + newJoe.getFax().getCode() + " " + newJoe.getFax().getNumber()); } }
总结:
使用xStream.alias(String elementName, Class cls)为任何一个自定义类创建到类到元素的别名(不是必须的,可以自己试一下);
使用xStream.toXML(Object obj)转换对象到XML;
使用xStream.fromXML(String xml)转换XML到对象