根据类名反射得到其属性及属性值,属性为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 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 + " ";}xml ="";return xml;}/*** 根据类名反射得到其属性及属性值* 属性为XML标签,属性值为XML标签值* @param objectList* @return String* @throws Exception*/public static String ObjecttoXML(List