一、前言
通过xstream源码包中com.thoughtworks.xstream.XStream、com.thoughtworks.xstream.io.xml.DomDriver定义XmlStreamUtil解析工具类,对实体对象和xml字符串间相互转换处理,详情代码示例。
二、代码示例
import com.thoughtworks.xstream.XStream;@b@import com.thoughtworks.xstream.io.xml.DomDriver;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.OutputStream;@b@@b@public class XmlStreamUtil@b@{@b@ private static String ENCODE = "utf-8";@b@@b@ public static String toXml(Object obj)@b@ {@b@ XStream xstream = new XStream();@b@@b@ xstream.processAnnotations(obj.getClass());@b@ return xstream.toXML(obj);@b@ }@b@@b@ public static <T> T toBean(String xmlStr, Class<T> cls)@b@ {@b@ XStream xstream = new XStream(new DomDriver());@b@ xstream.processAnnotations(cls);@b@ Object obj = xstream.fromXML(xmlStr);@b@ return obj;@b@ }@b@@b@ public static boolean toXMLFile(Object obj, String absPath, String fileName)@b@ throws IOException@b@ {@b@ String strXml = toXml(obj);@b@ String filePath = absPath + fileName;@b@ File file = new File(filePath);@b@ if (!(file.exists()))@b@ {@b@ file.createNewFile();@b@ }@b@@b@ OutputStream ous = null;@b@ try {@b@ ous = new FileOutputStream(file);@b@ ous.write(strXml.getBytes());@b@ ous.flush();@b@ } finally {@b@ if (ous != null)@b@ {@b@ ous.close();@b@ }@b@ }@b@@b@ return true;@b@ }@b@@b@ public static <T> T toBeanFromFile(String absPath, String fileName, Class<T> cls)@b@ throws Exception@b@ {@b@ String filePath = absPath + fileName;@b@ InputStream ins = null;@b@ try {@b@ ins = new FileInputStream(new File(filePath));@b@@b@ XStream xstream = new XStream(new DomDriver(ENCODE));@b@ xstream.processAnnotations(cls);@b@ Object obj = null;@b@ obj = xstream.fromXML(ins);@b@ Object localObject1 = obj;@b@@b@ return localObject1;@b@ }@b@ finally@b@ {@b@ if (ins != null)@b@ ins.close();@b@ }@b@ }@b@@b@ public static <T> T toBeanFromFile(File file, Class<T> cls)@b@ throws Exception@b@ {@b@ InputStream ins = null;@b@ try {@b@ ins = new FileInputStream(file);@b@@b@ XStream xstream = new XStream(new DomDriver(ENCODE));@b@ xstream.processAnnotations(cls);@b@ Object obj = null;@b@@b@ obj = xstream.fromXML(ins);@b@ Object localObject1 = obj;@b@@b@ return localObject1;@b@ }@b@ finally@b@ {@b@ if (ins != null)@b@ ins.close();@b@ }@b@ }@b@}