Ciao a tutt*.
Ho creato questo script che spero sia utile a chiunque abbia la necessità di convertire un documento XML in un oggetto JavaScript. Sono partito da uno script già fatto, ma l'ho migliorato parecchio... I due documenti qui postati vanno ovviamente creati nella stessa cartella!
documento da leggere (example.xml):
codice:
<ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="=">
<SD TITLE="A" FLAGS="" HOST="davidwalsh.name">
<TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
<LINKSIN NUM="1102"/>Hello
<SPEED TEXT="1421" PCT="51"/>World!
<FAVOURITE />
</SD>
<SD>
<POPULARITY URL="davidwalsh.name/" TEXT="7131"/>
<REACH RANK="5952"/>
<RANK DELTA="-1648"/>
</SD>
</ALEXA>
pagina HTML da cui avviene la lettura:
codice:
<html>
<head>
<title>XML to JavaScript Object conversion example</title>
<script type="text/javascript">
// a normal XMLHttpRequest function: it retrieves a file via XMLHTTPRequest, then calls fncCallback when done.
function XHR(sURL, fncCallback /*, argumentToPass1, argumentToPass2, etc. */) {
var oResp, aArgs = Array.prototype.slice.call(arguments, 2);
if (window.XMLHttpRequest) { oResp = new XMLHttpRequest(); }
else if (window.ActiveXObject) { oResp = new ActiveXObject("Microsoft.XMLHTTP"); }
if (oResp) {
if (fncCallback) {
if (typeof oResp.onload !== "undefined")
oResp.onload = function() {
fncCallback.apply(oResp, aArgs);
oResp = null;
};
else {
oResp.onreadystatechange = function() {
if (oResp.readyState === 4) {
fncCallback.apply(oResp, aArgs);
oResp = null;
}
};
}
}
oResp.open("GET", sURL, true);
oResp.setRequestHeader("Content-Type", "text/plain");
oResp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
oResp.send(null);
}
}
// recursive function which converts an XML DOM to a JavaScript Object
function xml2Obj (oXMLDom) {
var oRObj = true;
if (oXMLDom.nodeType === 3) { // text
oRObj = oXMLDom.nodeValue.replace(/^\s+|\s+$/g, "");
} else {
if (oXMLDom.nodeType === 1) { // element
// do attributes
if (oXMLDom.attributes.length > 0) {
var iAttrib;
oRObj = {};
oRObj["@attributes"] = {};
for (var iAttrId = 0; iAttrId < oXMLDom.attributes.length; iAttrId++) {
iAttrib = oXMLDom.attributes.item(iAttrId);
oRObj["@attributes"][iAttrib.nodeName] = iAttrib.nodeValue;
}
}
}
// do children
if (oXMLDom.hasChildNodes()) {
var iKey, iValue, iXMLNode;
if (oRObj === true) { oRObj = {}; }
for (var iChildId = 0; iChildId < oXMLDom.childNodes.length; iChildId++) {
iXMLNode = oXMLDom.childNodes.item(iChildId);
iKey = iXMLNode.nodeType === 3 ? "@content" : iXMLNode.nodeName;
iValue = xml2Obj(iXMLNode);
if (oRObj.hasOwnProperty(iKey)) {
if (iXMLNode.nodeType === 3) { oRObj[iKey] += iValue; }
else {
if (oRObj[iKey].constructor !== Array) { oRObj[iKey] = [oRObj[iKey]]; }
oRObj[iKey].push(iValue);
}
} else if (iXMLNode.nodeType !== 3 || iValue !== "") { oRObj[iKey] = iValue; }
}
}
}
return(oRObj);
};
// function called via ajax callback
function myFunction() {
// gets the object
var oMyObject = xml2Obj(this.responseXML);
// converts the object to a string and displays it in an alert message
alert(JSON.stringify(oMyObject));
}
</script>
</head>
<body>
<span onclick="XHR('example.xml', myFunction);" style="cursor: pointer;">Click me!</span></p>
</body>
</html>
carlomarx