Skip to content

Instantly share code, notes, and snippets.

@parris
Created June 8, 2012 20:31
Show Gist options
  • Save parris/2898000 to your computer and use it in GitHub Desktop.
Save parris/2898000 to your computer and use it in GitHub Desktop.
XML to JS Object (JSON), jQuery/jasmine
function xmlParser(node) {
var i = 0;
var attrs = node.attributes;
var nodes = node.childNodes;
var jsNode = new Object();
for(i;i<attrs.length;i++){
jsNode[attrs[i].name] = attrs[i].value;
}
i = 0;
for(i;i<nodes.length;i++){
if(nodes[i].nodeName == "#text"){
jsNode.textContent = node[i];
} else if (typeof jsNode[nodes[i].nodeName] !== "undefined") {
if (Object.prototype.toString.call(jsNode[nodes[i].nodeName]) === '[object Array]') {
jsNode[nodes[i].nodeName].add(xmlParser(nodes[i]));
} else {
jsNode[nodes[i].nodeName] = new Array(jsNode[nodes[i].nodeName]);
}
} else {
jsNode[nodes[i].nodeName] = xmlParser(nodes[i]);
}
}
if (typeof jsNode.textContent === "undefined"){
jsNode.textContent = "";
}
return jsNode;
}
parse($.parseXML(someXML).firstChild);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment