Convert XML to JSON using JavaScript
Convert XML to JSON effortlessly using JavaScript, enabling seamless integration and manipulation of XML data within your applications. JavaScript libraries like xml-js and xmldom Library simplify the conversion process, ensuring compatibility and efficiency.
Below are the approaches to convert XML to JSON in JavaScript:
Table of Content
Using xml-js Library
In this approach, we are using the xml-js library to handle XML to JSON conversion in JavaScript. This library provides a convenient 'xml2json' function, which directly transforms XML data into a JSON object. It offers options for formatting, including compactness and spacing.
Run the below command to install xml-js Library:
npm install xml-js
Example: The below example uses xml-js Library to convert XML to JSON in JavaScript.
const convert = require('xml-js');
const xmlData = `
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<genre>Fiction</genre>
</book>
`;
const jsonResult = convert.xml2json(xmlData, {
compact: true,
spaces: 2
});
console.log(jsonResult);
Output:
{
"book": {
"title": {
"_text": "The Great Gatsby"
},
"author": {
"_text": "F. Scott Fitzgerald"
},
"genre": {
"_text": "Fiction"
}
}
}
Using DOM Parser
In this approach, we are using the 'xmldom' library to handle XML parsing in JavaScript. This method involves parsing the XML data into a DOM structure and then traversing the nodes to extract element names and their corresponding text content. This method results in a JSON object representing the structure and content of the original XML data.
Run the below command to install xmldom Library:
npm install xmldom
Example: The below example uses DOM Parser to convert XML to JSON in JavaScript.
const { DOMParser } = require('xmldom');
const xmlString = `
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<genre>Fiction</genre>
</book>
`;
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();
}
}
console.log(JSON.stringify(data, null, 2));
Output:
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"genre": "Fiction"
}