使用xstream解析xml

前端之家收集整理的这篇文章主要介绍了使用xstream解析xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


public class XmlTool {

/** * 从xml文件中读取数据到javabean对象中 * * @param file * @param obj * @return */ public static Object fromXML(File file,Object obj) { XStream stream = null; FileInputStream input = null; InputStreamReader reader = null; Object object = null; try { stream = new XStream(new Dom4JDriver()); stream.alias(obj.getClass().getSimpleName(),obj.getClass()); input = new FileInputStream(file); reader = new InputStreamReader(input,Charset.forName("UTF-8")); object = stream.fromXML(reader,obj); } catch (Exception e) { e.printStackTrace(); } return object; } /** * 将javabean中封装的数据写到xml文件中 * @param obj * @param file */ public static void toXML(Object obj,File file) { XStream stream = null; FileOutputStream fos = null; OutputStreamWriter writer = null; try { stream = new XStream(new Dom4JDriver()); stream.alias(obj.getClass().getSimpleName(),obj.getClass()); fos = new FileOutputStream(file); writer = new OutputStreamWriter(fos,Charset.forName("UTF-8")); stream.toXML(obj,writer); } catch (Exception e) { e.printStackTrace(); } }

猜你在找的XML相关文章