实体类转换为XML字符串

前端之家收集整理的这篇文章主要介绍了实体类转换为XML字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

根据类名反射得到其属性属性值,属性为XML标签属性值为XML标签值。

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
/**
* 根据反射生成XML
* @author 喻克
*
*/
public class ObjectToXml {
/**
* 根据类名反射得到其属性属性值
* 属性为XML标签属性值为XML标签值
* @param object
* @return String
* @throws Exception
*/
public static String ObjecttoXML(Object object) throws Exception {
Class<? extends Object> classType = object.getClass();
//属性集合
Field[] fields = classType.getDeclaredFields();
String xml = "";
for (Field field : fields) {
String fieldName = field.getName();//属性名称
String stringLetter = fieldName.substring(0,1).toUpperCase();
// 获得object对象相应的get方法
String getName = "get" + stringLetter + fieldName.substring(1);
// 获取相应的方法
Method getMethod = classType.getMethod(getName,new Class[] {});
// 调用源对象的get方法的值
Object getValue = getMethod.invoke(object,new Object[] {});
if (null == getValue) {
getValue = "";
}
xml += "<" + fieldName + ">" + getValue + "</" + fieldName + ">";
}
xml ="<object>" +  xml + "</object>";
return xml;
}
/**
* 根据类名反射得到其属性属性值
* 属性为XML标签属性值为XML标签值
* @param objectList
* @return String
* @throws Exception
*/
public static String ObjecttoXML(List<Object> objectList) throws Exception {
String xml = "";
xml += "<objects>";
for (int i = 0; i < objectList.size(); i++) {
Object object = objectList.get(i);
Class<? extends Object> classType = object.getClass();
Field[] fields = classType.getDeclaredFields();
xml += "<object>";
for (Field field : fields) {
String fieldName = field.getName();
String stringLetter = fieldName.substring(0,1).toUpperCase();
String getName = "get" + stringLetter + fieldName.substring(1);
Method getMethod = classType.getMethod(getName,new Class[] {});
Object getValue = getMethod.invoke(object,new Object[] {});
if (null == getValue) {
getValue = "";
}
xml += "<" + fieldName + ">" + getValue + "</" + fieldName + ">";
}
xml += "</object>";
}
xml += "</objects>";
return xml;
}
}
原文链接:https://www.f2er.com/xml/299502.html

猜你在找的XML相关文章