JavaScript: convertire XML in JSON

Possiamo convertire una struttura XML in un oggetto JSON utilizzando una semplice funzione JavaScript ricorsiva. La funzione analizza i nodi di tipo elemento, testo e gli attributi della struttura XML per restituire un oggetto avente come proprietà e valori i nomi dei nodi e i loro valori. Vediamola insieme.

La funzione è la seguente:


function xmlToJSON(xml) {

	
	var obj = {}; // oggetto JSON da restituire

	if (xml.nodeType == 1) { // elemento
		// attributi
		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) { // testo
		obj = xml.nodeValue;
	}

	// discendenti dell'elemento
	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;
};

Si noti come in pratica questa funzione può anche essere applicata a strutture HTML. Il suo uso ideale è con AJAX.

Torna su