/**
* DMO4J写入XML
* @param obj 泛型对象
* @param entityPropertys 泛型对象的List集合
* @param Encode XML自定义编码类型(推荐使用GBK)
* @param XMLPathAndName XML文件的路径及文件名
*/
public
void writeXmlDocument
(T obj, List<T> entityPropertys, String Encode, String XMLPathAndName) {
//传一个bean过去
List<CopysearchProductBean> entityPropertys = new ArrayList<CopysearchProductBean>();CopysearchProductBean copysearchProductBean = new CopysearchProductBean();
copysearchProductBean.setPRODUCT_ID("000001");
copysearchProductBean.setPRODUCT_NAME("2013年11月19日113505Name");
CopysearchProductBean copysearchProductBean2 = new CopysearchProductBean();
copysearchProductBean2.setPRODUCT_ID("000002");
copysearchProductBean2.setPRODUCT_NAME("2013年11月19日113505Name2");
entityPropertys.add(copysearchProductBean);
entityPropertys.add(copysearchProductBean2);
long lasting = System.currentTimeMillis();
//效率检测
try {XMLWriter writer = null;// 声明写XML的对象
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");// 设置XML文件的编码格式
// String filePath = XMLPathAndName;//获得文件地址 用于写入xml的
// File file = new File(filePath);//获得文件 用于写入xml的
// if (file.exists()) {
// file.delete();
//
// }
// 新建student.xml文件并新增内容
Document document = DocumentHelper.createDocument();
String rootname = copysearchProductBean.getClass().getSimpleName();//获得类名
Element root = document.addElement(rootname + "s");//添加根节点
Field[] properties = copysearchProductBean.getClass().getDeclaredFields();//获得实体类的所有属性
for (CopysearchProductBean t : entityPropertys) { //递归实体
Element secondRoot = root.addElement(rootname); //二级节点
for (int i = 0; i < properties.length; i++) {
//反射get方法
Method meth = t.getClass().getMethod(
"get"
+ properties[i].getName().substring(0, 1)
.toUpperCase()
+ properties[i].getName().substring(1));
if (meth.invoke(t) != null && !"".equals(meth.invoke(t).toString())) {
//为二级节点添加属性,属性值为对应属性的值
secondRoot.addElement(properties[i].getName()).setText(
meth.invoke(t).toString());
} else {
continue;
}
}
}
//生成XML文件 用于写入xml的
// writer = new XMLWriter(new FileWriter(file), format);
writer = new XMLWriter();
writer.write(document);
writer.close();
System.out.println("输出xml格式的tostring+:" + writer.toString());
long lasting2 = System.currentTimeMillis();
System.out.println("写入XML文件结束,用时"+(lasting2 - lasting)+"ms");
} catch (Exception e) {
System.out.println("XML文件写入失败:" + e);
}
}
上面的代码是参考:http://www.cnblogs.com/tclee/archive/2012/02/28/2012773.html