Created
June 8, 2012 20:31
-
-
Save parris/2898000 to your computer and use it in GitHub Desktop.
XML to JS Object (JSON), jQuery/jasmine
This file contains 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 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