(In English: "Read XML into an associative array with JQuery")
Dejo a la disposición un pequeño ejemplo para leer un XML y asignar los datos a un arreglo asociativo de JavaScript (en dos dimensiones) usando JQuery.
Este es el XML de ejemplo:<catalog>
<cd id="cd-001">
<param name="title" value="Empire Burlesque" />
<param name="artist" value="Bob Dylan" />
<param name="country" value="USA" />
<param name="company" value="Columbia" />
<param name="price" value="10.90" />
<param name="year" value="1985" />
</cd>
<cd id="cd-002">
<param name="title" value="Hide your heart" />
<param name="artist" value="Bonnie Tyler" />
<param name="country" value="UK" />
<param name="company" value="CBS Records" />
<param name="price" value="9.90" />
<param name="year" value="1988" />
</cd>
<cd id="cd-003">
<param name="title" value="Greatest Hits" />
<param name="artist" value="Dolly Parton" />
<param name="country" value="USA" />
<param name="company" value="RCA" />
<param name="price" value="9.90" />
<param name="year" value="1982" />
</cd>
</catalog>
Y el código HTML/JQuery:<html>
<head>
<title>XML into associative array with JQuery</title>
<script type="text/javascript" src="jquery-1.5.2.min.js"></script>
<script type="text/javascript">
var cdArray = new Array(); // Will hold the XML data.
// Request to XML.
$.ajax({
type: "GET",
url: "cd-catalog.xml",
dataType: "xml",
async: false,
success: readXMLIntoArray
});
/**
Move XML data into associative array.
*/
function readXMLIntoArray(xml) {
$(xml).find('cd').each(function(){
var id = $(this).attr('id');
var parametersArray = new Array();
$(this).find('param').each(function(){
var name = $(this).attr('name');
var value = $(this).attr('value');
parametersArray[name] = value;
});
cdArray[id] = parametersArray;
});
}
// Testing array
document.write("<p>Title:" + cdArray["cd-002"]["title"] + "</p>");
document.write("<p>Artist:" + cdArray["cd-002"]["artist"] + "</p>");
</script>
</head>
<body>
</body>
</html>
Salida:Title:Hide your heartArtist:Bonnie Tyler