0

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.

2
  • 2
    How can you possibly miss this on google? davidwalsh.name/convert-xml-json Commented Dec 19, 2013 at 10:31
  • Besides, your json example isn't valid json. Commented Dec 19, 2013 at 10:32

2 Answers 2

2

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"}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Link-only answers are discouraged on SO. Please provide an example of how to use the tool you've linked to. Otherwise, this should be a comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.