Created
April 6, 2011 16:43
-
-
Save fearphage/906008 to your computer and use it in GitHub Desktop.
Changes XML to 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
| // Changes XML to JSON | |
| function xmlToJson(xml) { | |
| // Create the return object | |
| var obj = {}; | |
| if (xml.nodeType == 1) { // element | |
| // do attributes | |
| if (xml.attributes.length > 0) { | |
| obj["@attributes"] = {}; | |
| for (var j = 0; j < xml.attributes.length; j++) { | |
| obj["@attributes"][xml.attributes.item(j).nodeName] = xml.attributes.item(j).nodeValue; | |
| } | |
| } | |
| } else if (xml.nodeType == 3) { // text | |
| obj = xml.nodeValue; | |
| } | |
| // do children | |
| if (xml.hasChildNodes()) { | |
| for(var i = 0; i < xml.childNodes.length; i++) { | |
| if (typeof(obj[xml.childNodes.item(i).nodeName]) == "undefined") { | |
| obj[xml.childNodes.item(i).nodeName] = $xmlToJson(xml.childNodes.item(i)); | |
| } else { | |
| if (typeof(obj[xml.childNodes.item(i).nodeName].length) == "undefined") { | |
| var old = obj[xml.childNodes.item(i).nodeName]; | |
| obj[xml.childNodes.item(i).nodeName] = []; | |
| obj[xml.childNodes.item(i).nodeName].push(old); | |
| } | |
| obj[xml.childNodes.item(i).nodeName].push($xmlToJson(xml.childNodes.item(i))); | |
| } | |
| } | |
| } | |
| return obj; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment