How To Convert Xml To Json In Javascript

In this blog post, we will learn how to convert XML data to JSON format in JavaScript. This can be useful when you need to work with APIs that provide XML data, and you want to convert it to JSON for easier manipulation in your JavaScript code.

Step 1: Parse XML string

First, we need to parse the XML string using the DOMParser. This will convert the XML string to an XML Document object, which we can then traverse and process.

let parser = new DOMParser();
let xmlDoc = parser.parseFromString(xmlString, "text/xml");

Step 2: Convert XML Document object to JSON object

Next, we will create a function called xmlToJson that takes an XML node as input and returns a JSON object. The function will traverse the XML node tree recursively and build the corresponding JSON object.

function xmlToJson(xml) {
    let obj = {};

    // Handle node with attributes
    if (xml.hasAttributes()) {
        for (let i = 0; i < xml.attributes.length; i++) {
            obj[`@${xml.attributes[i].nodeName}`] = xml.attributes[i].nodeValue;
        }
    }

    // Handle child nodes
    if (xml.hasChildNodes()) {
        for (let i = 0; i < xml.childNodes.length; i++) {
            let item = xml.childNodes.item(i);
            let nodeName = item.nodeName;

            if (typeof (obj[nodeName]) === "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof (obj[nodeName].push) === "undefined") {
                    let old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    } else {
        obj = xml.textContent;
    }

    return obj;
}

Step 3: Convert JSON object to JSON string

Finally, we can use the JSON.stringify method to convert the JSON object generated by the xmlToJson function into a JSON string.

let jsonString = JSON.stringify(xmlToJson(xmlDoc));

Putting it all together

Here’s the complete code to convert an XML string to a JSON string:

// Parse XML string
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(xmlString, "text/xml");

// Convert XML Document object to JSON object
function xmlToJson(xml) {
    // ... (same as above)
}

// Convert JSON object to JSON string
let jsonString = JSON.stringify(xmlToJson(xmlDoc));

console.log(jsonString);

With this simple utility function, you can easily convert XML data to JSON format in your JavaScript projects. This can be especially useful when working with APIs that provide XML data, as JSON is generally easier to work with in JavaScript.

Happy coding!