1 import java.util.List; 2 3 import org.dom4j.Attribute; 4 import org.dom4j.Document; 5 import org.dom4j.DocumentException; 6 import org.dom4j.DocumentHelper; 7 import org.dom4j.Element; 8 9 import com.alibaba.fastjson.JSONArray; 10 import com.alibaba.fastjson.JSONObject; 11 12 /** 13 * xml工具類 14 * @author sleep 15 * @date 2016-09-13 16 */ 17 public class XmlTool { 18 19 /** 20 * String 轉 org.dom4j.Document 21 * @param xml 22 * @return 23 * @throws DocumentException 24 */ 25 public static Document strToDocument(String xml) throws DocumentException { 26 return DocumentHelper.parseText(xml); 27 } 28 29 /** 30 * org.dom4j.Document 轉 com.alibaba.fastjson.JSONObject 31 * @param xml 32 * @return 33 * @throws DocumentException 34 */ 35 public static JSONObject documentToJSONObject(String xml) throws DocumentException { 36 return elementToJSONObject(strToDocument(xml).getRootElement()); 37 } 38 39 /** 40 * org.dom4j.Element 轉 com.alibaba.fastjson.JSONObject 41 * @param node 42 * @return 43 */ 44 public static JSONObject elementToJSONObject(Element node) { 45 JSONObject result = new JSONObject(); 46 // 當前節點的名稱、文本內容和屬性 47 List<Attribute> listAttr = node.attributes();// 當前節點的所有屬性的list 48 for (Attribute attr : listAttr) {// 遍歷當前節點的所有屬性 49 result.put(attr.getName(), attr.getValue()); 50 } 51 // 遞歸遍歷當前節點所有的子節點 52 List<Element> listElement = node.elements();// 所有一級子節點的list 53 if (!listElement.isEmpty()) { 54 for (Element e : listElement) {// 遍歷所有一級子節點 55 if (e.attributes().isEmpty() && e.elements().isEmpty()) // 判斷一級節點是否有屬性和子節點 56 result.put(e.getName(), e.getTextTrim());// 沒有則將當前節點作為上級節點的屬性對待 57 else { 58 if (!result.containsKey(e.getName())) // 判斷父節點是否存在該一級節點名稱的屬性 59 result.put(e.getName(), new JSONArray());// 沒有則創建 60 ((JSONArray) result.get(e.getName())).add(elementToJSONObject(e));// 將該一級節點放入該節點名稱的屬性對應的值中 61 } 62 } 63 } 64 return result; 65 } 66 67 }