Convert XML to JSON with JavaScript
Convert XML data to JSON format in JavaScript using DOMParser, recursive parsing, and an interactive converter tool.
Interactive XML → JSON Converter
Paste your XML below and click Convert to get the JSON output instantly. This tool runs entirely in your browser using the DOMParser API.
How the Conversion Works
XML and JSON are both data interchange formats, but they differ in structure. XML uses nested tags with attributes, while JSON uses key-value pairs and arrays. Converting between them requires mapping XML elements to JSON properties.
Step 1 - Parse XML with DOMParser
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
// Check for parse errors
const error = xmlDoc.querySelector('parsererror');
if (error) {
console.error('Invalid XML:', error.textContent);
}
Step 2 - Recursive Node-to-Object Conversion
function xmlNodeToJson(node) {
// Text node → return trimmed string
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent.trim() || null;
}
const obj = {};
// Copy attributes as @attrName
for (const attr of node.attributes) {
obj['@' + attr.name] = attr.value;
}
// Recursively process child nodes
for (const child of node.childNodes) {
const key = child.nodeName;
const value = xmlNodeToJson(child);
if (value === null) continue;
// Handle repeated elements → array
if (obj[key]) {
if (!Array.isArray(obj[key])) obj[key] = [obj[key]];
obj[key].push(value);
} else {
obj[key] = value;
}
}
// Leaf node → return text content
if (Object.keys(obj).length === 0) {
return node.textContent.trim();
}
return obj;
}
const json = xmlNodeToJson(xmlDoc.documentElement);
console.log(JSON.stringify(json, null, 2));
Step 3 - Handling Edge Cases
Real-world XML often includes mixed content, CDATA sections, namespaces, and repeated child elements. Here are common patterns:
| XML Pattern | JSON Mapping |
|---|---|
| <item>text</item> | "item": "text" |
| <item id="1">text</item> | "item": {"@id":"1","#text":"text"} |
| Multiple <item> siblings | "item": ["val1","val2","val3"] |
| <![CDATA[raw]]> | Treated as text content |
JSON to XML (Reverse Conversion)
function jsonToXml(obj, rootName = 'root') {
let xml = '';
function convert(data, tag) {
if (typeof data === 'string' || typeof data === 'number') {
xml += `<${tag}>${data}${tag}>`;
} else if (Array.isArray(data)) {
data.forEach(item => convert(item, tag));
} else if (typeof data === 'object') {
xml += `<${tag}>`;
for (const [key, val] of Object.entries(data)) {
convert(val, key);
}
xml += `${tag}>`;
}
}
convert(obj, rootName);
return xml;
}
Using fetch() with XML APIs
Many APIs still return XML (SOAP services, RSS feeds, legacy systems). Here is how to fetch and convert on the fly:
async function fetchXmlAsJson(url) {
const response = await fetch(url);
const xmlText = await response.text();
const doc = new DOMParser()
.parseFromString(xmlText, 'text/xml');
return xmlNodeToJson(doc.documentElement);
}
// Example: fetch an RSS feed as JSON
const feed = await fetchXmlAsJson(
'https://example.com/rss.xml'
);
console.log(feed.channel.item);
Browser Support
DOMParser is supported in all modern browsers (Chrome, Firefox, Safari, Edge) and in Node.js via the xmldom package. For server-side Node.js, you can also use fast-xml-parser which handles conversion natively.
Last updated: 2026 • Browse all courses