Created
October 22, 2012 06:41
-
-
Save standingwave/3930001 to your computer and use it in GitHub Desktop.
convert xml to json
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 xmlToJson(xml_string) { | |
var json = {}; | |
if(xml_string.nodeType == 1) { // element | |
// do attributes | |
if(xml_string.attributes.length > 0) { | |
json["@attributes"] = {}; | |
for (var j = 0; j < xml_string.attributes.length; j++) { | |
var attribute = xml_string.attributes.item(j); | |
json["@attributes"][attribute.nodeName] = attribute.nodeValue; | |
} | |
} | |
} else if(xml_string.nodeType == 3) { // text | |
json = xml_string.nodeValue; | |
} | |
if(xml_string.hasChildNodes()) { | |
for(var i = 0; i < xml_string.childNodes.length; i++) { | |
var item = xml_string.childNodes.item(i); | |
var nodeName = item.nodeName; | |
if(typeof(json[nodeName]) == "undefined") { | |
json[nodeName] = xmlToJson(item); | |
} else { | |
if(typeof(json[nodeName].length) == "undefined") { | |
var old = json[nodeName]; | |
json[nodeName] = []; | |
json[nodeName].push(old); | |
} | |
json[nodeName].push(xmlToJson(item)); | |
} | |
} | |
} | |
return json; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is a great gist, thanks.