需要的jar包:xmlpull_1_0_5.jar,xstream-1.4.1.jar)
1、工具类XstreamUtil
package com.learn.util;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
*
* @ClassName: XstreamUtil.java
* @Description:
* @author: fengzf fengzf@gstarcad.com
* @Date: 2016年12月6日
*
*/
publicclass XstreamUtil {
/**
* 将bean转换为xml
* @param obj 转换的bean
*@return bean转换为xml
*/
publicstatic String objectToXml(Object obj) {
XStream xStream = new XStream();
// xstream使用注解转换
xStream.processAnnotations(obj.getClass());
returnxStream.toXML(obj);
}
/**
* 将xml转换为bean
* @param<T> 泛型
* @param xml 要转换为bean的xml
* @param cls bean对应的Class
* @return xml转换为bean
*/
publicstatic <T> T xmlToObject(String xml, Class<T> cls) {
XStream xstream = new XStream(new DomDriver());
// xstream使用注解转换
xstream.processAnnotations(cls);
return (T) xstream.fromXML(xml);
}
}
2、Java普通实体类转xml
实体类Message.java代码
package com.learn.entity;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Response")
publicclass Message {
@XStreamAlias("returncode")
private String returnCode;
@XStreamAlias("returnmessage")
private String returnMessage;
@XStreamAlias("status")
privateintstatus;
@XStreamAlias("time")
private String reqTime;
public String getReturnCode() {
returnreturnCode;
}
publicvoid setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public String getReturnMessage() {
returnreturnMessage;
}
publicvoid setReturnMessage(String returnMessage) {
this.returnMessage = returnMessage;
}
publicint getStatus() {
returnstatus;
}
publicvoid setStatus(intstatus) {
this.status = status;
}
public String getReqTime() {
returnreqTime;
}
publicvoid setReqTime(String reqTime) {
this.reqTime = reqTime;
}
}
3、XML字符串转实体
@XStreamAlias使用
一、 特点:
简化的API;
无映射文件;
高性能,低内存占用;
整洁的XML;
不需要修改对象;支持内部私有字段,不需要setter/getter方法
提供序列化接口;
自定义转换类型策略;
二、 使用场景
Transport转换
Persistence 持久化对象
Configuration 配置
Unit Tests 单元测试
Interface服务之间XML消息的交互