package com.tartary.turbo.core.util; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.security.AnyTypePermission; /** * @Description XStream實現xml和對象互相轉換的工具 * @ClassName XStreamUtil * @author yewenting2013@foxmail.com * @date 2017年8月24日 下午2:19:19 * */ public class XStreamUtil { private static String XML_TAG = "<?xml version='1.0' encoding='UTF-8'?>"; /** * Description: 私有化構造 */ private XStreamUtil() { super(); } /** * @Description 為每次調用生成一個XStream * @Title getInstance * @return */ private static XStream getInstance() { XStream xStream = new XStream(new DomDriver("UTF-8")) { /** * 忽略xml中多余字段 */ @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { @SuppressWarnings("rawtypes") @Override public boolean shouldSerializeMember(Class definedIn, String fieldName) { if (definedIn == Object.class) { return false; } return super.shouldSerializeMember(definedIn, fieldName); } }; } }; // 設置默認的安全校驗 XStream.setupDefaultSecurity(xStream); // 使用本地的類加載器 xStream.setClassLoader(XStreamUtil.class.getClassLoader()); // 允許所有的類進行轉換 xStream.addPermission(AnyTypePermission.ANY); return xStream; } /** * @Description 將xml字符串轉化為java對象 * @Title xmlToBean * @param xml * @param clazz * @return */ public static <T> T xmlToBean(String xml, Class<T> clazz) { XStream xStream = getInstance(); xStream.processAnnotations(clazz); Object object = xStream.fromXML(xml); T cast = clazz.cast(object); return cast; } /** * @Description 將java對象轉化為xml字符串 * @Title beanToXml * @param object * @return */ public static String beanToXml(Object object) { XStream xStream = getInstance(); xStream.processAnnotations(object.getClass()); // 剔除所有tab、制表符、換行符 String xml = xStream.toXML(object).replaceAll("\\s+", " "); return xml; } /** * @Description 將java對象轉化為xml字符串(包含xml頭部信息) * @Title beanToXml * @param object * @return */ public static String beanToXmlWithTag(Object object) { String xml = XML_TAG + beanToXml(object); return xml; } /** * 測試main方法 */ public static void main(String[] args) { } }