Xstream使用示例【将对象序列化为XML和将XML反序列为对象】
Xstream资源下载地址:http://xstream.codehaus.org/download.html
必须包:xstream-1.3.1.jar
测试程序
Person.java
- <span style="font-size: large;">package com.xstream.test;
-
- public class Person {
- private String firstName;
- private String lastName;
- private PhoneNumber phonex;
- private PhoneNumber 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;
- }
-
- }
- </span>
PhoneNumber.java
- <span style="font-size: large;">package com.xstream.test;
-
- public class PhoneNumber {
-
- private int code;
- private int number;
-
- public PhoneNumber(int code, int number) {
- 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;
- }
-
- }
- </span>
XstreamTest.java
- <span style="font-size: large;">package com.xstream.test;
-
- import com.thoughtworks.xstream.XStream;
- import com.thoughtworks.xstream.io.xml.DomDriver;
-
- public class XstreamTest {
-
-
-
-
-
-
-
-
- public static void main(String[] args) {
- XStream xStream = new XStream(new DomDriver());
- Person joe = new Person("Joe","Walnes");
- joe.setPhonex(new PhoneNumber(123,222));
- joe.setFax(new PhoneNumber(123,444));
-
-
-
- xStream.alias("person",Person.class);
-
- String xml=xStream.toXML(joe);
- System.out.println("对象序列化为XML:\n"+xml);
-
- Person newJoe = (Person)xStream.fromXML(xml);
- System.out.println("XML反序列化为对象:\n"+newJoe);
- }
-
-
-
- }
- </span>