XStream简介
XStream
是一个Java
对象与XML
互相转换的工具类库。
官网链接: http://x-stream.github.io/index.html
简单使用
下载页面:http://x-stream.github.io/download.html
使用Maven
构建项目的加入以下依赖:
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.10</version>
</dependency>
创建Bean
:
public class User {
private String userName;
private String email;
public User() {}
public User(String userName, String email) {
this.userName = userName;
this.email = email;
}
public String toString() {
return "User:{userName=" + this.userName + ",email=" + this.email + "}";
}
//Getter and Setter...
}
Java
对象转XML
:
使用xStream.toXML()
方法。
public static void main(String[] args) {
User user = new User("lanweihong", "lwhhhp@gmail.com");
//创建解析XML对象
XStream xStream = new XStream();
//设置别名, 默认会输出全路径
xStream.alias("User", User.class);
//转为xml
String xml = xStream.toXML(user);
System.out.println(xml);
}
转换后的xml
文本为:
<User>
<userName>lanweihong</userName>
<email>lwhhhp@gmail.com</email>
</User>
XML
转Java
对象
使用xStream.fromXML()
方法。
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("User", User.class);
String xml = "<User>\n" +
" <userName>lanweihong</userName>\n" +
" <email>lwhhhp@gmail.com</email>\n" +
"</User>";
//转对象
User user = (User)xStream.fromXML(xml);
System.out.println(user.toString());
}
输出文本为:
User:{userName=lanweihong,email=lwhhhp@gmail.com}
使用注解
最基本的注解@XStreamAlias
用于设置字段别名;我们将上述例子创建的User
对象添加注解改造一下:
@XStreamAlias("user")
public class User {
@XStreamAlias("username")
private String userName;
@XStreamAlias("email")
private String email;
public User() {}
public User(String userName, String email) {
this.userName = userName;
this.email = email;
}
public String toString() {
return "User:{userName=" + this.userName + ",email=" + this.email + "}";
}
//Getter and Setter...
}
XStream
默认不会读取这个注解,因为,我们需要声明XStream
的注解来源:
public static void main(String[] args) {
User user = new User("lanweihong", "lwhhhp@gmail.com");
XStream xStream = new XStream();
//声明XStream注解来源
xStream.processAnnotations(User.class);
String xml = xStream.toXML(user);
System.out.println(xml);
}
输出文本为:
<user>
<username>lanweihong</username>
<email>lwhhhp@gmail.com</email>
</user>
由此可见,生成的xml
节点名称已经变为我们使用@XStreamAlias
注解的别名。
简单封装为工具类
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class XmlUtils {
/**
* XML转对象
* @param clazz 对象类
* @param str xml字符串
* @param <T> T
* @return
*/
public static <T> T parseFromXml(Class<T> clazz, String xml) {
//创建解析XML对象
XStream xStream = new XStream(new DomDriver());
//处理注解
xStream.processAnnotations(clazz);
@SuppressWarnings("unchecked")
//将XML字符串转为bean对象
T t = (T)xStream.fromXML(xml);
return t;
}
/**
* 对象转xml
* @param obj 对象
* @return
*/
public static String toXml(Object obj) {
XStream xStream = new XStream(new DomDriver());
xStream.processAnnotations(obj.getClass());
return xStream.toXML(obj);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。