Last active
February 27, 2020 07:23
-
-
Save svdamani/d7fc513abc31f13242e03cec929950c8 to your computer and use it in GitHub Desktop.
Convert XML document to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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