引入pom
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.19</version>
</dependency>
工具类
package com.xm.demo.util.xml;
import com.thoughtworks.xstream.XStream;
/**
* @ClassName: XmlUtils2
* @Description: XML和兑换互转简化版(基于xstream)
* @author mengxc
* @date 2022年4月8日 下午2:27:07
*/
public class XmlUtils {
/**
* @Title: toBean
* @Description: 将xml字符串转为对象
* @param <T> 目标对象泛型
* @param clazz 转换后目标对象clazz
* @param xml 待转换XML
* @return 转换后目标对象
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public static <T> T toBean(Class<?> clazz, String xml) {
T xmlObject = null;
XStream xstream = new XStream();
XStream.setupDefaultSecurity(xstream);
xstream.processAnnotations(clazz);
xstream.autodetectAnnotations(true);
xstream.allowTypesByRegExp(new String[] { ".*" });
xmlObject = (T) xstream.fromXML(xml);
return xmlObject;
}
/**
* @Title: toXml
* @Description: 将对象转为xml字符串
* @param obj 待转换为xml的对象
* @return xml
*/
@SuppressWarnings("deprecation")
public static String toXml(Object obj) {
XStream xstream = new XStream();
XStream.setupDefaultSecurity(xstream);
xstream.autodetectAnnotations(true);//自动检测模式,默认
xstream.allowTypesByRegExp(new String[] { ".*" });
return xstream.toXML(obj);
}
/**
* @Title: toXml
* @Description: 将对象转为xml字符串(带头信息)
* @param obj 带转换为xml的对象
* @param charSet 编码
* @return xml
*/
@SuppressWarnings("deprecation")
public static String toXml(Object obj, String charSet) {
XStream xstream = new XStream();
xstream.autodetectAnnotations(true);//自动检测模式,默认
XStream.setupDefaultSecurity(xstream);
xstream.allowTypesByRegExp(new String[] { ".*" });
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"").append(charSet.toUpperCase()).append("\"?>\n")
.append(xstream.toXML(obj));
return sb.toString();
}
}
测试类
@Test
public void test3() {
Response result = XmlUtils.toBean(Response.class, xml);
log.info("XML转对象3:{}", result);
}
@Test
public void test4() {
Response resp = new Response();
resp.setCode(200);
resp.setMsg("操作成功");
resp.setResult(true);
String xml = XmlUtils.toXml(resp);
log.info("对象转XML4:{}", xml);
}
@Test
public void test5() {
Response resp = new Response();
resp.setCode(200);
resp.setMsg("操作成功");
resp.setResult(true);
String xml = XmlUtils.toXml(resp,"gbk");
log.info("对象转XML5:{}", xml);
}