Snippets

Convert XML to JSON with JavaScript

Useful function to convert xml into 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++) {
				var attribute = xml.attributes.item(j);
				obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
			}
		}
	} else if (xml.nodeType == 3) { // text
		obj = xml.nodeValue;
	}

	// do children
	if (xml.hasChildNodes()) {
		for(var i = 0; i < xml.childNodes.length; i++) {
			var item = xml.childNodes.item(i);
			var nodeName = item.nodeName;
			if (typeof(obj[nodeName]) == "undefined") {
				obj[nodeName] = xmlToJson(item);
			} else {
				if (typeof(obj[nodeName].length) == "undefined") {
					var old = obj[nodeName];
					obj[nodeName] = [];
					obj[nodeName].push(old);
				}
				obj[nodeName].push(xmlToJson(item));
			}
		}
	}
	return obj;
};

Source: http://davidwalsh.name/convert-xml-json...

Share this snippet

 
  • http://markussandy.com Markus Sandy

    This site is a rip-off! Why do you steal other people’s content? Why not publish a useful review and properly credit the author (not just a link)? Instead you just steal the code and leave out the important points. You are a disservice to the community. You vampires suck!

    • http://www.wprecipes.com Jean-Baptiste Jung

      It’s compiling, not stealing. Why do I ALWAYS credit authors with a link to the original post if I wanted to steal?

      Aniways, thanks for letting me know your opinion. Cheers!

    • Ech0riginal

      Dude , he credits each original author with a link after each post.
      Keep your ignorance to yourself.