Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert XML to JSON String in JavaScript?
Some popular formats for data exchange are XML (eXtensible Markup Language) and JSON (JavaScript Object Notation). Tags are used to structure XML, while JSON is a more condensed key-value format. In JavaScript apps, converting XML data to JSON is often required to facilitate data manipulation or integration with APIs that expect JSON format.
Several techniques for converting XML to JSON using JavaScript are examined in this article, from using DOM parsing to employing custom JavaScript solutions.
Understanding XML and JSON
XML Example
<person>
<name>Pankaj</name>
<age>20</age>
<city>Surat</city>
</person>
JSON Equivalent
{
"person": {
"name": "Pankaj",
"age": "20",
"city": "Surat"
}
}
The XML data has a hierarchical structure, while the JSON version uses nested objects. Converting between these formats involves parsing XML tags and attributes to create key-value pairs.
Using DOMParser and Recursion
DOMParser API parses XML strings into DOM objects, making it easier to traverse and convert them into JSON format.
function xmlToJson(xml) {
let obj = {};
if (xml.nodeType === 1) { // Element node
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (let i = 0; i < xml.attributes.length; i++) {
const attribute = xml.attributes[i];
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType === 3) { // Text node
return xml.nodeValue.trim();
}
if (xml.hasChildNodes()) {
for (let i = 0; i < xml.childNodes.length; i++) {
const item = xml.childNodes.item(i);
const nodeName = item.nodeName;
if (item.nodeType === 3 && item.nodeValue.trim() === "") continue;
if (typeof(obj[nodeName]) === "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) === "undefined") {
obj[nodeName] = [obj[nodeName]];
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
const xmlString = `<person>
<name>Pankaj</name>
<age>20</age>
<city>Surat</city>
</person>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
const jsonResult = xmlToJson(xmlDoc.documentElement);
console.log(JSON.stringify(jsonResult, null, 2));
{
"name": "Pankaj",
"age": "20",
"city": "Surat"
}
Using Third-Party Libraries
Libraries like xml2json or fast-xml-parser can simplify conversion, especially for complex XML structures. These libraries handle edge cases and provide configuration options.
// Example using fast-xml-parser (npm install fast-xml-parser)
const { XMLParser } = require('fast-xml-parser');
const xmlString = `<person>
<name>Pankaj</name>
<age>20</age>
<city>Surat</city>
</person>`;
const parser = new XMLParser();
const jsonObj = parser.parse(xmlString);
console.log(JSON.stringify(jsonObj, null, 2));
Using Custom Regex Parser
For simple XML structures, a custom regex-based parser can be lightweight and efficient.
function simpleXmlToJson(xml) {
const obj = {};
// Remove outer wrapper if exists
xml = xml.replace(/<\?xml.*?\?>/g, '').trim();
// Match simple tags like <tag>value</tag>
const regex = /<([^\/>\s]+)[^>]*>([^<]+)<\/\1>/g;
let match;
while ((match = regex.exec(xml))) {
const tagName = match[1];
const value = match[2].trim();
obj[tagName] = value;
}
return obj;
}
const xmlString = `<person>
<name>Pankaj</name>
<age>20</age>
<city>Surat</city>
</person>`;
const result = simpleXmlToJson(xmlString);
console.log(JSON.stringify(result, null, 2));
{
"name": "Pankaj",
"age": "20",
"city": "Surat"
}
Handling Complex XML Features
Real-world XML often contains attributes, arrays, and nested structures that require special handling:
function advancedXmlToJson(xml) {
let obj = {};
if (xml.nodeType === 1) {
// Handle attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (let attr of xml.attributes) {
obj["@attributes"][attr.nodeName] = attr.nodeValue;
}
}
// Handle child elements
if (xml.hasChildNodes()) {
for (let child of xml.childNodes) {
if (child.nodeType === 3) { // Text node
const text = child.nodeValue.trim();
if (text) obj["#text"] = text;
} else if (child.nodeType === 1) { // Element node
const childName = child.nodeName;
const childObj = advancedXmlToJson(child);
if (obj[childName]) {
if (!Array.isArray(obj[childName])) {
obj[childName] = [obj[childName]];
}
obj[childName].push(childObj);
} else {
obj[childName] = childObj;
}
}
}
}
}
return obj;
}
const complexXml = `<books>
<book id="1" category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>
<book id="2" category="science">
<title>Cosmos</title>
<author>Carl Sagan</author>
</book>
</books>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(complexXml, "application/xml");
console.log(JSON.stringify(advancedXmlToJson(xmlDoc.documentElement), null, 2));
{
"book": [
{
"@attributes": {
"id": "1",
"category": "fiction"
},
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"@attributes": {
"id": "2",
"category": "science"
},
"title": "Cosmos",
"author": "Carl Sagan"
}
]
}
Comparison of Methods
| Method | Complexity | Handles Attributes | Performance | Best For |
|---|---|---|---|---|
| DOMParser + Recursion | Medium | Yes | Good | Complex XML structures |
| Third-party Libraries | Low | Yes | Excellent | Production applications |
| Custom Regex | Low | No | Very Good | Simple XML structures |
Conclusion
Converting XML to JSON in JavaScript can be accomplished through multiple approaches. Use DOMParser for complex XML with attributes and nested structures, third-party libraries for production applications, or simple regex parsing for basic XML formats. Choose the method that best fits your specific use case and performance requirements.
