今天看到在Android上面写的一个程序,解析xml使用的是XStream技术,以前没有听说过,今天来把它学习一下,对于简单的使用来说这个是比较简单的。这个例子是参照官网上面的例子写的:http://xstream.codehaus.org/tutorial.html
1.首先构造想要序列化的类
Person.java:
public class Person { private String firstname; private String lastname; private PhoneNumber phone; private PhoneNumber fax; // ... constructors and methods public Person(String firstname, String lastname) { super(); this.firstname = firstname; this.lastname = lastname; } public void setPhone(PhoneNumber phoneNumber) { this.phone = phoneNumber; } public void setFax(PhoneNumber phoneNumber) { this.fax = phoneNumber; } @Override public String toString() { return "FirstName:" + firstname + ",LastName:" + lastname + "phone.Code:" + phone.getCode() + "phone.Number:" + phone.getNumber() + "fax:" + fax.getCode() + "fax.Number:" + fax.getNumber(); } }
PhoneNumber.java:
public class PhoneNumber { private int code; private String number; // ... constructors and methods public PhoneNumber(int code, String number) { super(); this.code = code; this.number = number; } public int getCode() { return code; } public String getNumber() { return number; } }
2.初始化XStream并序列化和反序列化。
Stream xStream = new XStream();
你需要xstream-[version].jar and xpp3-[version].jar在classpath中。XPP3是一个非常快的XML拉式转换器工具。如果你不想包含这个依赖,你可以使用标准的JAXP DOM转换器来代替。
XStream xStream = new XStream(new DomDriver());//不需要XPP3库
这里要特别说明的是XStream xStream2=new XStream();这样会出错,使用原来的
public class XStreamTest { public static void main(String[] args) throws FileNotFoundException { //Initializing XStream XStream xStream=new XStream(); xStream.alias("person", Person.class); xStream.alias("personnumber", PhoneNumber.class); //Serializing an object to XML Person joe = new Person("Joe", "Walnes"); joe.setPhone(new PhoneNumber(123, "1234-456")); joe.setFax(new PhoneNumber(123, "9999-999")); FileOutputStream fileOutputStream=new FileOutputStream(new File("test.xml")); xStream.toXML(joe,fileOutputStream); //Deserializing an object back from XM XStream xStream2=new XStream(); FileInputStream fileInputStream=new FileInputStream(new File("test.xml")); Person person=(Person)xStream.fromXML(fileInputStream); System.out.println(person.toString()); } }
看一下运行的结果:
test.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>
反序列化在控制台输出的结果:
FirstName:Joe,LastName:Walnesphone.Code:123phone.Number:1234-456fax:123fax.Number:9999-999