Created
December 23, 2019 09:19
-
-
Save bitsmanent/4370432401e780513be662a4125737a7 to your computer and use it in GitHub Desktop.
Parse an XML object into JSON
This file contains hidden or 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
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