且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Javascript,Jquery将XML转换为Json对象

更新时间:2021-12-28 09:50:24

我们从字符串中的XML数据开始:

We start with the XML Data in a string:

var xmlStr = 
  '<root><fl val="A_Value">AAAAAAAAAA</fl>' + 
  '<fl val="B_Value">' + 
  '  <![CDATA["BBBBBBBB"]]>' + 
  '</fl>' + 
  '<fl val="C_Value">CCCCCCCCCC</fl>' + 
  '<fl val="D_Value">DDDDDDDDDD</fl></root>';

将字符串转换为 XML doc对象

var parseXml;

if (window.DOMParser) {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}

var xmlDoc = parseXml(xmlStr);

然后将XML doc对象转换为JSON

function xmlToJson(xml) {
    // Create the return object
    var obj = {};

    // console.log(xml.nodeType, xml.nodeName );

    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } 
    else if (xml.nodeType == 3 || 
             xml.nodeType == 4) { // text and cdata section
        obj = xml.nodeValue
    }

    // do children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].length) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                if (typeof(obj[nodeName]) === 'object') {
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
    }
    return obj;
}

var theJson = xmlToJson(xmlDoc);
console.log(JSON.stringify(theJson));
/*
"{"root":{"fl":[{"@attributes":{"val":"A_Value"},"#text":{}},{"@attributes":{"val":"B_Value"},"#text":{},"#cdata-section":"\"BBBBBBBB\""},{"@attributes":{"val":"C_Value"},"#text":{}},{"@attributes":{"val":"D_Value"},"#text":{}}]}}"
*/

然后将对象转换为您想要的结构:

Then transform the object to your desired structure:

var transformed = {};
var elements = theJson.root.fl;
for(var i=0; i<elements.length; i++) {
    var element = elements[i];
    transformed[element["#text"].trim().length > 0 ? 
        element["#text"] : 
        element["#cdata-section"]] = element["@attributes"]["val"];
}
console.log(JSON.stringify(transformed));
//{"AAAAAAAAAA":"A_Value","\"BBBBBBBB\"":"B_Value","CCCCCCCCCC":"C_Value","DDDDDDDDDD":"D_Value"}