XML解析---利用XStream解析xml数据及反构造Java对象

时间:2021-12-15 23:28:26

XStream 是一个轻量级的、简单易用的开放源代码 Java库,用于将 Java 对象序列化为 XML 或者再转换回来。而且XStream还能将java对象转成其它格式,比如JSon。

需要用到的包:xstream-1.3.1

下载链接:http://xstream.codehaus.org/download.html

测试:

新建Person类----

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;
}
public Person() {
} 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 getPhone() {
return phone;
} public void setPhone(PhoneNumber phone) {
this.phone = phone;
} public PhoneNumber getFax() {
return fax;
} public void setFax(PhoneNumber fax) {
this.fax = fax;
}
}

新建PhoneNumber类:

public class PhoneNumber {
private int code;
private String number; public PhoneNumber(int code, String number) {
this.code = code;
this.number = number;
}
public PhoneNumber() { }
public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public String getNumber() {
return number;
} public void setNumber(String number) {
this.number = number;
}
}

写主方法进行测试:

public class Main {
/**
* @kxm
*/
public static void main(String[] args) {
XStream xstream = new XStream(new DomDriver());
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 newJoe = (Person) xstream.fromXML(xml);
System.out.println(newJoe.getLastname());
}
}

打印结果:

XML解析---利用XStream解析xml数据及反构造Java对象