Allora, per il parsing dell'XML esistono molti modi. Cmq il più pratico è il responseXML dell'oggetto XMLHttpRequest, che restituisce il foglio XML già parsato. Per quanto riguarda la lettura del contenuto del file XML le cose si complicano. Il metodo nativo è XPath, ma è molto complicato da usare. Un'alternativa a XPath è questa funzione che avevo scritto tempo fa per il Mozilla Developer Center che trasforma un documento XML già parsato in un albero di oggetti javascript (in gergo questo metodo si chiama JXON, "Javascript XML Object Notation"). Te la incollo qui:
codice:
function buildValue(sValue) {
if (/^\s*$/.test(sValue)) { return(null); }
if (/^(true|false)$/i.test(sValue)) { return(sValue.toLowerCase() === "true"); }
if (isFinite(sValue)) { return(parseFloat(sValue)); }
if (isFinite(Date.parse(sValue))) { return(new Date(sValue)); }
return(sValue);
}
function getXMLData (oXMLParent) {
var /* TRUE is the default value for empty nodes */ vResult = true; nLength = 0, sTxtContent = "";
if (oXMLParent.hasAttributes()) {
vResult = {};
for (nLength; nLength < oXMLParent.attributes.length; nLength++) {
iAttrib = oXMLParent.attributes.item(nLength);
vResult["@" + iAttrib.nodeName.toLowerCase()] = buildValue(iAttrib.nodeValue.replace(/^\s+|\s+$/g, ""));
}
}
if (oXMLParent.hasChildNodes()) {
var iKey, iValue, iXMLChild;
for (var iChildId = 0; iChildId < oXMLParent.childNodes.length; iChildId++) {
iXMLChild = oXMLParent.childNodes.item(iChildId);
if (iXMLChild.nodeType === 1 && !iXMLChild.prefix) {
if (nLength === 0) { vResult = {}; }
iKey = iXMLChild.nodeName.toLowerCase();
iValue = getXMLData(iXMLChild);
if (vResult.hasOwnProperty(iKey)) {
if (vResult[iKey].constructor !== Array) { vResult[iKey] = [vResult[iKey]]; }
vResult[iKey].push(iValue);
} else { vResult[iKey] = iValue; nLength++; }
} else if (iXMLChild.nodeType === 3) { sTxtContent += iXMLChild.nodeValue.replace(/^\s+|\s+$/g, ""); }
else if (iXMLChild.nodeType === 4) { sTxtContent += iXMLChild.nodeValue; }
}
}
if (nLength > 0) { vResult.keyValue = buildValue(sTxtContent); Object.freeze(vResult); }
else if (sTxtContent) { vResult = buildValue(sTxtContent); }
return(vResult);
}
var oAlbero = getXMLData(oResponseXML);
// abbiamo ottenuto il nostro albero di oggetti javascript! provare per credere: alert(JSON.stringify(oAlbero));
La funzione è davvero molto semplice da utilizzare. La conversione avviene secondo la «convenzione di Parker». Se vuoi approfondire e capire di cosa si tratta: http://code.google.com/p/xml2json-xs...nsformingRules. Ci sono alcune piccole differenze con la mia funzione, come ad esempio il fatto che i nodi vuoti e senza attributi avranno come valore true invece di null (mi sembrava più sensato
).
Per quanto riguarda il preload, se ho capito bene, non si può fare quello che chiedi, visto che l'informazione su quali immagini caricare è contenuta nel file XML. Ma chiarisci meglio questo punto.