There are many examples of how to load an XML file in JavaScript, they include the load function of type document:
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e)
{
alert(e.message);
}
}
xmlDoc.async=false;
xmlDoc.load("localfile.xml");
safari will error out on the last line of this code. xmlDoc.load is not part of the w3c standard. Instead use xmlDoc.open.
req = false;
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
req = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", "localfile.xml", true);
req.send("");
}
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
parseXML();
} else {
alert("There was a problem retrieving the XML data:\n" +
req.status);
}
}
}
This method is called from loadXMLDoc and is passed the string to the URL. Then the code it will execute when the file is opened will be at parseXML(). Also, make note that in this second example, if you want to run getElementsByTagTame, you will want to rn them on req.responseXML instead of xmlDoc.

No comments:
Post a Comment