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(); } } 原文链接:https://www.f2er.com/xml/298595.html