package com.dom4j;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Xml2Object<T>{
public static void main(String[] args){
Xml2Object d=new Xml2Object();
User user=new User();
User user1=new User("姓名1",18,"男");
User user2=new User("姓名2",19,"女");
User user3=new User("石头",20,"女");
List<User> users=new ArrayList<User>();
users.add(user1);
users.add(user2);
users.add(user3);
try {
d.writeXmlDocument(user, users, "GBK", "WebRoot/xml/student.xml");
} catch (Exception e) {
System.out.println("生成xml失败");
e.printStackTrace();
}
/*
Xml2Object<User> d=new Xml2Object<User>();
User user=new User();
List<User> list=d.readXML("WebRoot/xml/student.xml",user);
System.out.println("XML文件读取结果:");
for(int i=0;i<list.size();i++){
User username=(User)list.get(i);
System.out.println("name"+username.getName());
System.out.println("age"+username.getAge());
System.out.println("sex"+username.getSex());
}*/
}
@SuppressWarnings("hiding")
public <T> void writeXmlDocument(T obj,List<T> entityPropertys,String Encode,String XMLPathAndName) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException{
long lasting=System.currentTimeMillis();
XMLWriter writer=null;
OutputFormat format=OutputFormat.createCompactFormat();
format.setEncoding(Encode);//设置XML文件的编码方式
String filePath=XMLPathAndName;
File file=new File(filePath);
if(file.exists()){
file.delete();
}
Document document=DocumentHelper.createDocument();
String rootname=obj.getClass().getSimpleName();
Element root=document.addElement(rootname+"s");
Field[] properties=obj.getClass().getDeclaredFields();
for(T t:entityPropertys){
Element secondRoot=root.addElement(rootname);
for(int i=0;i<properties.length;i++){
Method meth=t.getClass().getMethod(
"get"
+properties[i].getName().substring(0,1).toUpperCase()
+properties[i].getName().substring(1)
);
secondRoot.addElement(
properties[i].getName()
).setText(meth.invoke(t).toString());
}
}
writer =new XMLWriter(new FileWriter(file),format);
writer.write(document);
writer.close();
long lasting2=System.currentTimeMillis();
System.out.println("写入XML文件结束,用时"+(lasting2-lasting)+"ms");
}