简单介绍下JAVA对象与XML互相转变,详细请进入http://xstream.codehaus.org/tutorial.html
1、首先下载需要用的jar包:xstream-1.3.1.jar,并放置在ClassPath目录下
2、用到的两到JavaBean:
/** * File : PhoneNumber.java * Author : zqding * Date : 2011-1-21 * Version: * Desc : */ package org.usc.beans; public class PhoneNumber { private int code; private String number; public PhoneNumber(){ } public PhoneNumber(int code,String number){ this.code = code; this.number = number; } 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; } }
/** * File : Person.java * Author : zqding * Date : 2011-1-21 * Version: * Desc : */ package org.usc.beans; public class Person { private String firstname; private String lastname; private PhoneNumber phone; private PhoneNumber fax; public Person(){ } public Person(String name,String lname){ this.firstname = name; this.lastname = lname; } 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; } }
3、测试代码:
/** * File : ObjectToXML.java * Author : zqding * Date : 2011-1-21 * Version: * Desc : */ package org.usc.reflection; import org.usc.beans.Person; import org.usc.beans.PhoneNumber; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver;; public class ObjectToXML { public static void main(String[] args) { //1、对象转变成XML Person person = new Person("Joe", "Walnes"); person.setPhone(new PhoneNumber(123, "1234-456")); person.setFax(new PhoneNumber(123, "9999-999")); XStream xStream=new XStream(new DomDriver()); xStream.alias("person",Person.class); String xml=xStream.toXML(person); System.out.println(xml); //2、XML转变成对象 Person newJoe = (Person)xStream.fromXML(xml); System.out.println(newJoe.getFirstname()); System.out.println(newJoe.getPhone().getNumber()); } }
4、显示结果:
<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> Joe 1234-456