Skip to content

Instantly share code, notes, and snippets.

@svdamani
Last active February 27, 2020 07:23
Show Gist options
  • Save svdamani/d7fc513abc31f13242e03cec929950c8 to your computer and use it in GitHub Desktop.
Save svdamani/d7fc513abc31f13242e03cec929950c8 to your computer and use it in GitHub Desktop.
Convert XML document to JSON
// const xmlDoc = new DOMParser().parseFromString(xmlString, 'text/xml');
function xmlToJson(xml) {
const parseAll = s => (s && ((!isNaN(s) && parseFloat(s)) || (Date.parse(s) && new Date(s)))) || s.trim();
const nodesToJson = function(nodes) {
return Array.from(nodes || [])
.map(item => ({
name: item.nodeName,
value: item.nodeType === Node.ATTRIBUTE_NODE ? parseAll(item.nodeValue) : xmlToJson(item)
}))
.filter(item => item.value)
.reduce((result, { name, value }) => {
if (typeof result[name] === 'undefined') {
result[name] = value;
} else {
if (typeof result[name].push === 'undefined') {
result[name] = [result[name]];
}
result[name].push(value);
}
return result;
}, Object.create(null));
};
if (xml.nodeType === Node.TEXT_NODE) return parseAll(xml.nodeValue);
const attributes = xml.nodeType === Node.ELEMENT_NODE ? nodesToJson(xml.attributes) : {},
children = xml.hasChildNodes() ? nodesToJson(xml.childNodes) : {},
result = { ...attributes, ...children };
return Object.keys(result).length === 1 ? Object.values(result)[0] : result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment