【分享】Object对象转换为XML

利用反射的方法将Object对象转换为XML字符串:
根据类名反射得到其属性属性值,属性为XML标签属性值为XML标签值。

01importjava.lang.reflect.Field;
02importjava.lang.reflect.Method;
03importjava.util.List;
04
05publicclassObjectToXml {
06/**
07* 根据类名反射得到其属性属性
08* 属性为XML标签属性值为XML标签
09* @param object
10* <a href="http://home.51cto.com/index.php?s=/space/34010" target="_blank">@return</a> String
11* <a href="http://home.51cto.com/index.php?s=/space/2305405" target="_blank">@throws</a> Exception
12*/
13publicstaticString ObjecttoXML(Object object) throwsException {
14Class<? extendsObject> classtype = object.getClass();
15//属性集合
16Field[] fields = classtype.getDeclaredFields();
17String xml = "";
18for(Field field : fields) {
19String fieldName = field.getName();//属性名称
20String stringLetter = fieldName.substring(0,1).toupperCase();
21// 获得object对象相应的get方法
22String getName = "get"+ stringLetter + fieldName.substring(1);
23// 获取相应的方法
24Method getmethod = classtype.getmethod(getName,newClass[] {});
25// 调用源对象的get方法的值
26Object getValue = getmethod.invoke(object,newObject[] {});
27if(null== getValue) {
28getValue = "";
29}
30xml += "<"+ fieldName + ">"+ getValue + "</"+ fieldName + ">";
31}
32xml ="<object>"+ xml + "</object>";
33returnxml;
34}
35
36/**
37* 根据类名反射得到其属性属性
38* 属性为XML标签属性值为XML标签
39* @param objectList
40* <a href="http://home.51cto.com/index.php?s=/space/34010" target="_blank">@return</a> String
41* <a href="http://home.51cto.com/index.php?s=/space/2305405" target="_blank">@throws</a> Exception
42*/
43publicstaticString ObjecttoXML(List<Object> objectList) throwsException {
44String xml = "";
45xml += "<objects>";
46for(inti = 0; i < objectList.size(); i++) {
47Object object = objectList.get(i);
48Class<? extendsObject> classtype = object.getClass();
49Field[] fields = classtype.getDeclaredFields();
50xml += "<object>";
51for(Field field : fields) {
52String fieldName = field.getName();
53String stringLetter = fieldName.substring(0,1).toupperCase();
54String getName = "get"+ stringLetter + fieldName.substring(1);
55Method getmethod = classtype.getmethod(getName,newClass[] {});
56Object getValue = getmethod.invoke(object,newObject[] {});
57if(null== getValue) {
58getValue = "";
59}
60xml += "<"+ fieldName + ">"+ getValue + "</"+ fieldName + ">";
61}
62xml += "</object>";
63}
64xml += "</objects>";
65returnxml;
66}
67}

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念