Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Created December 23, 2019 09:19
Show Gist options
  • Save bitsmanent/4370432401e780513be662a4125737a7 to your computer and use it in GitHub Desktop.
Save bitsmanent/4370432401e780513be662a4125737a7 to your computer and use it in GitHub Desktop.
Parse an XML object into JSON
function xmltojson(xml, attkey = "$") {
var obj = {}, t, len, i;
switch(xml.nodeType) {
case Node.ELEMENT_NODE:
len = xml.attributes.length;
if(len) {
obj[attkey] = {};
for(i = 0; i < len; ++i) {
t = xml.attributes[i];
obj[attkey][t.nodeName] = t.nodeValue;
}
}
break;
case Node.TEXT_NODE:
return xml.nodeValue;
}
if(xml.hasChildNodes()) {
xml.childNodes.forEach((c) => {
if(!obj[c.nodeName])
obj[c.nodeName] = [];
obj[c.nodeName].push(xmltojson(c));
});
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment