【分享】Object对象转换为XML

前端之家收集整理的这篇文章主要介绍了【分享】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}
原文链接:https://www.f2er.com/xml/299840.html

猜你在找的XML相关文章