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 }