前端之家收集整理的这篇文章主要介绍了
Object和xml互转,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/** * Object和xml互转 **/
public class XmlUtil {
/** * xml文档Document转对象 * * @param document * @param clazz * @return */
public static Object getObject(Document document,Class<?> clazz) {
Object obj = null;
Element root = document.getRootElement();
try {
obj = clazz.newInstance();
Field[] field = clazz.getDeclaredFields();
List<Element> properties = root.elements();
for (Element pro : properties) {
String propertyname = pro.getName();
String propertyvalue = pro.getText();
for (Field field1 : field) {
if (field1.getName().equals(propertyname)) {
String mName = propertyname.substring(0,1).toUpperCase() + propertyname.substring(1);
Method m = obj.getClass().getMethod("set" + mName,String.class);
m.invoke(obj,propertyvalue);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/** * xml字符串转对象 * * @param xmlString * @param clazz * @return */
public static Object getObject(String xmlString,Class<?> clazz) throws Exception {
Document document = null;
try {
document = DocumentHelper.parseText(xmlString);
} catch (DocumentException e) {
throw new Exception("获取Document异常" + xmlString);
}
return getObject(document,clazz);
}
/** * 对象转xml文件 * * @param b * @return */
public static Document getDocument(Object b) {
Document document = DocumentHelper.createDocument();
try {
Element root = document.addElement(b.getClass().getSimpleName());
Field[] field = b.getClass().getDeclaredFields();
for (int j = 0; j < field.length; j++) {
String name = field[j].getName();
if (!name.equals("serialVersionUID")) {
String methodName = name.substring(0,1).toUpperCase() + name.substring(1);
Method m = b.getClass().getMethod("get" + methodName);
String propertievalue = (String) m.invoke(b);
Element propertie = root.addElement(name);
if(propertievalue == null){
propertie.setText("");
}else{
propertie.setText(propertievalue);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return document;
}
/** * 对象转xml格式的字符串 * * @param b * @return */
public static String getXmlString(Object b) {
return getDocument(b).asXML();
}
}
原文链接:https://www.f2er.com/xml/293329.html