xstream实现JAVA对象和XML的相互转化
xstream实现JAVA对象和XML的相互转化
首页
http://xstream.codehaus.org/
文档
http://xstream.codehaus.org/converter-tutorial.html
下载得到文件
xstream-distribution-1.3.1-bin.zip
如果是用MAVEN2来管理,那么pom.xml文件需要导入以下包
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.3.1</version>
</dependency>
参考官方网站上的文档,其实已经很清楚了
一个JAVA的POJO类
package com.sillycat.easybase.mock;
import java.util.Date;
public class Person {
private String name;
private String email;
private Date gmtCreate;
...省略了get和set方法
}
一个工具类
package com.sillycat.easybase.utils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class XmlUtil {
//将对象转为XML
public static String simpleobject2xml(Object obj) {
XStream xStream = new XStream(new DomDriver());
xStream.alias(obj.getClass().getSimpleName(), obj.getClass());
String xml = xStream.toXML(obj);
return xml;
}
//将XML转为对象
public static Object simplexml2object(String xml,Object obj) {
XStream xStream = new XStream(new DomDriver());
xStream.alias(obj.getClass().getSimpleName(), obj.getClass());
Object reobj = xStream.fromXML(xml);
return reobj;
}
}
一个测试类
package com.sillycat.easybase.mock;
import java.util.Date;
import com.sillycat.easybase.utils.XmlUtil;
public class PersonTest {
public static void main(String[] args) {
Person person = new Person();
person.setName("sillycat");
person.setEmail("test@test.com");
person.setGmtCreate(new Date());
String xml = XmlUtil.simpleobject2xml(person);
System.out.println(xml);
Person temp = (Person) XmlUtil.simplexml2object(xml,new Person());
System.out.println(temp);
System.out.println(temp.getName());
System.out.println(temp.getEmail());
System.out.println(temp.getGmtCreate());
}
}