大神们帮我看看这个为什么是空的呢?调试看到不是空的呀..
xml test.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
</root>
user.java
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;
}
}
XMLUtil.java
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];
/**
* 将属性名称赋值给数组
*/
for(int i=0;i<fields.length;i++){
fieldNames[i]=fields[i].getName();
str[i]=getFieldValueByName(fieldNames[i],u);
}
el1.addAttribute(fieldNames[0], str[0].toString());
for (int i = 1; i < fieldNames.length; i++) {
// el1.element(fieldNames[i]).addText(str[i].toString());(这句报错.但是调试不是空的)
el1.addElement(i+"s").addText((i+10)+"y");//使用这个就没问题
}
OutputFormat format=OutputFormat.createPrettyPrint();
try {
FileOutputStream fs=new FileOutputStream("src/test.xml");
XMLWriter xw=new XMLWriter(fs,format);
xw.write(doc);
xw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据属性名获取属性值
* */
private Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {
return null;