简体   繁体   中英

Convert XML to Json Object using Javascript,Jquery

I need to convert xml to json.

My XML data is:

<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>

I would like to convert this to json:

{
   AAAAAAAAAA : A_Value,
   BBBBBBBB   : B_Value,
   CCCCCCCCCC : C_Value,
   DDDDDDDDDD : D_Value
}

Can anyone please help me. Thanks.

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>';

Convert the string to an XML doc object :

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);

Then convert the XML doc object to 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"}

The XML to JSON Plugin (jQuery.xml2json) is a script you can use to convert simple XML into a JSON object. It will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM