Skip to content

Instantly share code, notes, and snippets.

@CreativeNotice
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CreativeNotice/ae21f93762ee746c5cd1 to your computer and use it in GitHub Desktop.
Save CreativeNotice/ae21f93762ee746c5cd1 to your computer and use it in GitHub Desktop.
Allows you to convert a cfml xml document into a structure.
/**
* @author Raymond Camden
* @see http://www.raymondcamden.com/index.cfm/2012/1/4/Converting-XML-to-JSON--My-exploration-into-madness
* @updated Ryan Mueller
* @hint Fixes some issues with the original code, though I don't remember what they were ;-)
* @returntype Struct
*/
public function xmlToStruct(xml x) {
var s = {};
if(xmlGetNodeType(x) == "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 {
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;
}
}
}
}
return s;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment