dom4j將xml轉換成物件
阿新 • • 發佈:2018-12-22
dom4j將xml轉換成物件
package test; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.tree.DefaultAttribute; public class XmlUtil { /** * xml字串轉換成bean物件 * * @param xmlStr xml字串 * @param clazzMap 待轉換的class包括物件屬性的class * @return 轉換後的物件 */ public static Object xmlStrToBean(String xmlStr,Map<String,Class> clazzMap) { Object obj = null; try { // 將xml格式的資料轉換成Map物件 Map<String, Object> map = new HashMap<String, Object>(); //將xml格式的字串轉換成Document物件 Document doc = DocumentHelper.parseText(xmlStr); //獲取根節點 Element root = doc.getRootElement(); //將map物件的資料轉換成Bean物件 obj = mapToBean(root, clazzMap); } catch(Exception e) { e.printStackTrace(); } return obj; } /** * 將Map物件通過反射機制轉換成Bean物件 * * @param clazzMap 待轉換的class包括物件屬性的class * @return 轉換後的Bean物件 * @throws Exception 異常 */ public static Object mapToBean( Element root,Map<String,Class> clazzMap) throws Exception { //獲取根節點下的所有元素 List children = root.elements(); List<DefaultAttribute> attrs= root.attributes(); Map<String, Object> map = new HashMap<String, Object>(); if(children != null && children.size() > 0) { for(int i = 0; i < children.size(); i++) { Element child = (Element)children.get(i); if(!child.isTextOnly()){ Object ob= mapToBean(child,clazzMap); map.put(child.getName(),ob); }else{ map.put(child.getName(), child.getTextTrim()); } } } for(DefaultAttribute att:attrs){ map.put(att.getName(),att.getText()); } Class clazz=clazzMap.get(root.getName()); Object obj = clazz.newInstance(); if(map != null && map.size() > 0) { for(Map.Entry<String, Object> entry : map.entrySet()) { String propertyName = entry.getKey(); Object value = entry.getValue(); String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); Field field = getClassField(clazz, propertyName); Class fieldTypeClass = field.getType(); value = convertValType(value, fieldTypeClass); clazz.getMethod(setMethodName, field.getType()).invoke(obj, value); } } return obj; } /** * 將Object型別的值,轉換成bean物件屬性裡對應的型別值 * * @param value Object物件值 * @param fieldTypeClass 屬性的型別 * @return 轉換後的值 */ private static Object convertValType(Object value, Class fieldTypeClass) { Object retVal = null; if(Long.class.getName().equals(fieldTypeClass.getName()) || long.class.getName().equals(fieldTypeClass.getName())) { retVal = Long.parseLong(value.toString()); } else if(Integer.class.getName().equals(fieldTypeClass.getName()) || int.class.getName().equals(fieldTypeClass.getName())) { retVal = Integer.parseInt(value.toString()); } else if(Float.class.getName().equals(fieldTypeClass.getName()) || float.class.getName().equals(fieldTypeClass.getName())) { retVal = Float.parseFloat(value.toString()); } else if(Double.class.getName().equals(fieldTypeClass.getName()) || double.class.getName().equals(fieldTypeClass.getName())) { retVal = Double.parseDouble(value.toString()); } else { retVal = value; } return retVal; } /** * 獲取指定欄位名稱查詢在class中的對應的Field物件(包括查詢父類) * * @param clazz 指定的class * @param fieldName 欄位名稱 * @return Field物件 */ private static Field getClassField(Class clazz, String fieldName) { if( Object.class.getName().equals(clazz.getName())) { return null; } Field []declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { if (field.getName().equals(fieldName)) { return field; } } Class superClass = clazz.getSuperclass(); if(superClass != null) {// 簡單的遞迴一下 return getClassField(superClass, fieldName); } return null; } public static String getXML(){ StringBuffer sb=new StringBuffer(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sb.append("<note name=\"xian\">"); sb.append("<to>George</to>"); sb.append("<Student>"); sb.append("<name>xian</name>"); sb.append("<classRoom>"); sb.append("<name>Ap111111</name>"); sb.append("</classRoom>"); sb.append("<age>13</age>"); sb.append("</Student>"); sb.append("<from>John</from>"); sb.append("<heading>Reminder</heading>"); sb.append("<Body>Don't forget the meeting!</Body>"); sb.append("</note>"); return sb.toString(); } public static void main(String[] args){ Map<String ,Class> mapClass=new HashMap<String,Class>(); mapClass.put("note", Note.class); mapClass.put("Student", Student.class); mapClass.put("classRoom", ClassRoom.class); Note note=(Note)xmlStrToBean(getXML(),mapClass); System.out.println(note.getName()+"--"+note.getTo()+"--"/*+note.getStudent().getAge()+note.getStudent().getClassRoom().getName()*/); } }
public class Note {
public String to;
public String from;
public String heading;
public String Body;
public String name;
public Student Student;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
}
public void setFrom(String from) {
this.from = from;
}
public String getHeading() {
return heading;
}
public void setHeading(String heading) {
this.heading = heading;
}
public String getBody() {
return Body;
}
public void setBody(String body) {
}
public Student getStudent() {
return Student;
}
public void setStudent(Student student) {
Student = student;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package test;
public class Student {
public String name;
public String age;
public ClassRoom classRoom;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public ClassRoom getClassRoom() {
return classRoom;
}
public void setClassRoom(ClassRoom classRoom) {
this.classRoom = classRoom;
}
}
package test;
public class ClassRoom {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}