需要的maven 依賴
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>
dome:
package com.oce.util;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class StringAnalysisXml {
/**
* String 轉 org.dom4j.Document
* @param xml
* @return
* @throws DocumentException
*/
public static Document strToDocument(String xml){
try {
//加上xml標籤是爲了獲取最外層的標籤,如果不需要可以去掉
return DocumentHelper.parseText(xml);
} catch (DocumentException e) {
return null;
}
}
/**
* org.dom4j.Document 轉 com.alibaba.fastjson.JSONObject
* @param xml
* @return
* @throws DocumentException
*/
public static JSONObject documentToJSONObject(String xml){
return elementToJSONObject(strToDocument(xml).getRootElement());
}
/**
* org.dom4j.Element 轉 com.alibaba.fastjson.JSONObject
* @param node
* @return
*/
public static JSONObject elementToJSONObject(Element node) {
JSONObject result = new JSONObject();
// 當前節點的名稱、文本內容和屬性
List<Attribute> listAttr = node.attributes();// 當前節點的所有屬性的list
for (Attribute attr : listAttr) {// 遍歷當前節點的所有屬性
result.put(attr.getName(), attr.getValue());
}
// 遞歸遍歷當前節點所有的子節點
List<Element> listElement = node.elements();// 所有一級子節點的list
if (!listElement.isEmpty()) {
for (Element e : listElement) {// 遍歷所有一級子節點
if (e.attributes().isEmpty() && e.elements().isEmpty()) // 判斷一級節點是否有屬性和子節點
result.put(e.getName(), e.getTextTrim());// 沒有則將當前節點作爲上級節點的屬性對待
else {
if (!result.containsKey(e.getName())) // 判斷父節點是否存在該一級節點名稱的屬性
result.put(e.getName(), new JSONArray());// 沒有則創建
((JSONArray) result.get(e.getName())).add(elementToJSONObject(e));// 將該一級節點放入該節點名稱的屬性對應的值中
}
}
}
return result;
}
}