Skip to content

Instantly share code, notes, and snippets.

@howellcc
Last active November 9, 2016 19:38
Show Gist options
  • Save howellcc/fac8ab9ad769c701b8b01c2dce8cf252 to your computer and use it in GitHub Desktop.
Save howellcc/fac8ab9ad769c701b8b01c2dce8cf252 to your computer and use it in GitHub Desktop.
This borrows heavily from the work by Ray Camden https://www.raymondcamden.com/2012/01/04/Converting-XML-to-JSON-My-exploration-into-madness https://gist.github.com/cfjedimaster/4580449 and redherring917 https://gist.github.com/redherring917/7929512 I had noticed that if the ending leaf was an array that the first element would be returned prope…
/*
This borrows heavily from the work by Ray Camden
https://www.raymondcamden.com/2012/01/04/Converting-XML-to-JSON-My-exploration-into-madness
https://gist.github.com/cfjedimaster/4580449
and redherring917 https://gist.github.com/redherring917/7929512
I had noticed that if the ending leaf was an array that the first element would be returned properly, but the subsequent values in the array would be return as a struct.
*/
function xmlToStruct(xml x) {
var s = {};
if(xmlGetNodeType(x) == "DOCUMENT_NODE") {
writeoutput("document node");
s[structKeyList(x)] = xmlToStruct(x[structKeyList(x)]);
}
if(structKeyExists(x, "xmlAttributes") && !structIsEmpty(x.xmlAttributes)) {
s.attributes = {};
for(var item in x.xmlAttributes) {
s.attributes[item] = x.xmlAttributes[item];
}
}
if(structKeyExists(x, "xmlText") && len(trim(x.xmlText))) {
s.value = x.xmlText;
}
if(structKeyExists(x, "xmlChildren") && arrayLen(x.xmlChildren)) {
for(var i=1; i<=arrayLen(x.xmlChildren); i++) {
if(structKeyExists(s, x.xmlchildren[i].xmlname)) {
if(!isArray(s[x.xmlChildren[i].xmlname])) {
var temp = s[x.xmlchildren[i].xmlname];
s[x.xmlchildren[i].xmlname] = [temp];
}
arrayAppend(s[x.xmlchildren[i].xmlname], xmlToStruct(x.xmlChildren[i]));
} else {
//before we parse it, see if simple
if(structKeyExists(x.xmlChildren[i], "xmlChildren") && arrayLen(x.xmlChildren[i].xmlChildren)) {
s[x.xmlChildren[i].xmlName] = xmlToStruct(x.xmlChildren[i]);
} else if(structKeyExists(x.xmlChildren[i],"xmlAttributes") && !structIsEmpty(x.xmlChildren[i].xmlAttributes)) {
s[x.xmlChildren[i].xmlName] = xmlToStruct(x.xmlChildren[i]);
} else {
s[x.xmlChildren[i].xmlName] = x.xmlChildren[i].xmlText;
}
}
}
} else {
//If we're returning just xmlText with no children we need to return just the value, not a struct.
return s.value;
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment