日期:2014-05-17 浏览次数:20750 次
<?xml version="1.0" encoding="UTF-8"?>
<root>
</root>
package com.test.entity;
public class User {
private Integer id;
private String name;
private String passWord;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public User() {
}
public User(Integer id, String name, String passWord) {
this.id = id;
this.name = name;
this.passWord = passWord;
}
}
package com.test.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.test.entity.User;
public class XMLUtil {
/**
* @param args
*/
public static void main(String[] args) {
User u=new User(1,"張三","123");
new XMLUtil().initDocument(u);
System.exit(0);
}
public Document getDocument(){
SAXReader saxreader=new SAXReader();
Document doc=null;
File file=new File("src/test.xml");
if(file.exists()){
try {
doc=saxreader.read(file);
} catch (DocumentException e) {
e.printStackTrace();
}
}
return doc;
}
/**
*
* 初始化xml文件
* @param u
*/
public void initDocument(Object u){
Document doc=this.getDocument();
Element el=doc.getRootElement();
Element el1=el.addElement(u.getClass().getSimpleName().toString());
Field[] fields=u.getClass().getDeclaredFields();
String[] fieldNames=new String[fields.length];
Object str[]=new Object[fields.length];
/**
* 将属性名称赋值给数组
*/