gistfile1.txt import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import java.lang.reflect.Field;import java.lang.reflect.Method;/** * Created by full on 2017/10/13. */public class Xml { public static void mai
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Created by full on 2017/10/13.
*/
public class Xml {
public static void main(String[] args) {
File b = new File();
b.setName("image.png");
b.setPath("/root/image.png");
b.setType("image");
Document document = DocumentHelper.createDocument();
try {
// 创建根节点元素
Element root = document.addElement("xml");
Field[] field = b.getClass().getDeclaredFields(); // 获取实体类b的所有属性,返回Field数组
for (int j = 0; j < field.length; j++) { // 遍历所有有属性
String name = field[j].getName(); // 获取属属性的名字
if (!name.equals("serialVersionUID")) {//去除串行化序列属性
name = name.substring(0, 1).toUpperCase()
+ name.substring(1); // 将属性的首字符大写,方便构造get,set方法
Method m = b.getClass().getMethod("get" + name);
// System.out.println("属性get方法返回值类型:" + m.getReturnType());
String propertievalue = (String) m.invoke(b);// 获取属性值
Element propertie = root.addElement(name);
propertie.addCDATA(propertievalue);
}
}
System.out.println(document.asXML());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class File{
String name;
String path;
String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
