XML (Extensible Markup Language) is widely used for enterprise configurations and legacy web services (like SOAP). However, modern web systems, REST APIs, and JavaScript applications utilize JSON for data exchange. Converting XML schemas and tag trees into clean JSON objects is a essential task. This guide outlines how to perform this client-side.
XML vs. JSON: Key Differences
XML is tag-based and supports attributes on elements, comments, and schemas. JSON is key-value based, less verbose, and maps directly to native JavaScript types. Converting XML elements to JSON offers:
- Better Readability: JSON structures are much more compact and easier to read.
- Native JS Parsing: JSON is natively parsed in JavaScript via
JSON.parse(), whereas XML requires DOM parsing. - Reduced Payload: Eliminating closing tags reduces string transfer sizes by up to 50%.
Parsing XML to JSON in the Browser
We can use the browser's built-in DOMParser to validate and parse XML strings into a Document Object Model, and then recursively traverse the tree to build a matching JSON object.
Recursive JS XML-to-JSON Parser
Here is a complete recursive function to parse XML text into a nested JavaScript Object:
function xmlToJson(xmlString) {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
// Check for parse errors
const parserError = xmlDoc.getElementsByTagName("parsererror");
if (parserError.length > 0) {
throw new Error("Invalid XML document structure.");
}
const nodeToValue = (node) => {
const children = Array.from(node.children);
if (children.length === 0) {
return node.textContent?.trim() || "";
}
const obj = {};
// Extract attributes
for (let i = 0; i < node.attributes.length; i++) {
const attr = node.attributes[i];
obj[`@${attr.name}`] = attr.value;
}
// Process child tags
const groups = {};
for (const child of children) {
if (!groups[child.tagName]) {
groups[child.tagName] = [];
}
groups[child.tagName].push(child);
}
for (const [tag, list] of Object.entries(groups)) {
if (list.length === 1) {
obj[tag] = nodeToValue(list[0]);
} else {
obj[tag] = list.map(nodeToValue);
}
}
return obj;
};
return nodeToValue(xmlDoc.documentElement);
}
// Example usage
const xml = `Alice `;
console.log(xmlToJson(xml));
Convert XML to JSON using Sylvaera
For instant conversion of complex markup files without writing manual functions, use Sylvaera's XML to JSON converter. It recursively formats attributes, tags, and value arrays locally on your device for fast, private processing.