1. 程式人生 > 實用技巧 >【推薦】com.alibaba方式xml轉json,能將xml的所有屬性方法,全部轉化為json

【推薦】com.alibaba方式xml轉json,能將xml的所有屬性方法,全部轉化為json

推薦,這種轉化方法,能將xml的所有屬性方法,全部轉化為json

<dependency>
	<groupId>dom4j</groupId>
	<artifactId>dom4j</artifactId>
	<version>1.6.1</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.1.41</version>
</dependency>

  

工具類

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 XmlTool {
	/**
     * String 轉 org.dom4j.Document
     * @param xml
     * @return
     * @throws DocumentException
     */
    public static Document strToDocument(String xml){
        try {
        	//加上xml標籤是為了獲取最外層的標籤,如果不需要可以去掉
			return DocumentHelper.parseText("<xml>"+xml+"</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;
    }
}

  

測試:

public static void main(String[] args) {
		String result = "<applications>"
						+"<versions__delta>1</versions__delta>"
						+"<apps__hashcode></apps__hashcode>"
						+"</applications>";
	       
	   System.out.println(XmlTool.documentToJSONObject(result).toJSONString());
	       
	       
}