Skip to content

Instantly share code, notes, and snippets.

@fearphage
Created April 6, 2011 16:43
Show Gist options
  • Select an option

  • Save fearphage/906008 to your computer and use it in GitHub Desktop.

Select an option

Save fearphage/906008 to your computer and use it in GitHub Desktop.
Changes XML to JSON
// 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