Open In App

How to Convert XML to JSON in JavaScript?

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

To convert XML to JSON in JavaScript, various methods and libraries and be used. Here, we use xml-js library that provides xml2json function to convert XML to JSON data. It takes XML data as input and gives the JSON objects as output. We can also use the DOMParser from the xmldom package to convert the XML to JSON object.

Convert XML to JSON using xml-js Library

The xml-js library converts the XML file to JSON in JavaScript. The xml2json function from the library takes XML data as input and converts it into a JSON object, with options like compact formatting and spacing specified.

Run the below command to install xml-js Library:

npm install xml-js

The added dependency after installing xml-js is

"dependencies": {
"xml-js": "^1.6.11"
}

Example: The xml-js library converts the XML to JSON format with a compact representation and formatted with 2 spaces.

JavaScript
// index.js

const convert = require('xml-js');
const xmlData = `
<data>
    <organization>GeeksforGeeks</organization>
    <founder>Sandeep Jain</founder>
    <location>Noida</location>
</data>
`;

const jsonResult = convert.xml2json(xmlData, {
    compact: true,
    spaces: 2
});

console.log(jsonResult);

Output

{
"data": {
"organization": {
"_text": "GeeksforGeeks"
},
"founder": {
"_text": "Sandeep Jain"
},
"location": {
"_text": "Noida"
}
}
}

Convert XML to JSON using DOM Parser

The xmldom library's DOMParser is used to parse XML data in JavaScript. It traverse the parsed XML document's nodes to extract element names and their corresponding text content, storing them in a JSON object for conversion and formatting.

Run the below command to install xmldom Library:

npm install xmldom

The added dependency after installing xmldom is

"dependencies": {
"xmldom": "^0.6.0"
}

Example: Parses the given XML string to a JavaScript object using xmldom and then converts it to a formatted JSON string.

JavaScript
// index.js

const { DOMParser } = require('xmldom');
const xmlString = `
    <data>
        <organization>GeeksforGeeks</organization>
        <founder>Sandeep Jain</founder>
        <location>Noida</location>
    </data>
`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
const data = {};
const nodes = xmlDoc.documentElement.childNodes;

for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.nodeType === 1) {
        data[node.nodeName] = node.textContent.trim();
    }
}

const jsonResult = JSON.stringify(data, null, 2);
console.log(jsonResult);

Output

{
"organization": "GeeksforGeeks",
"founder": "Sandeep Jain",
"location": "Noida"
}

Next Article

Similar Reads

three90RightbarBannerImg
  翻译: