Skip to content

Instantly share code, notes, and snippets.

@IanSSenne
Last active May 27, 2020 03:55
Show Gist options
  • Save IanSSenne/01b55fd34a45c3973b5c6bbb26f0db1b to your computer and use it in GitHub Desktop.
Save IanSSenne/01b55fd34a45c3973b5c6bbb26f0db1b to your computer and use it in GitHub Desktop.
const SingleValue = Symbol("XML_TRANSPORT_VALUE")
function xmlNodeToObject(node) {
let res = {
...Array.from(node.children).map(xmlNodeToObject).reduce((a, v) => {
const val = v[SingleValue] ? v.$_value : v;
if (Array.isArray(a[v.$_.nodeName])) {
a[v.$_.nodeName].push(val);
} else if (a[v.$_.nodeName]) {
a[v.$_.nodeName] = [a[v.$_.nodeName], val];
} else {
a[v.$_.nodeName] = val;
}
return a;
}, {}),
$_attributes: new Map(Array.from(node.attributes).map(_ => ([_.name, _.value]))),
$_value: node.children.length === 0 ? node.childNodes[0] ? node.childNodes[0].nodeValue : (Array.from(node.attributes).reduce((a, v) => {
a[v.name] = v.value;
return a
}, {})) : null,
$_: node,
[SingleValue]: node.children.length === 0
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment