↑
Main Page
XmlDom
With this code added, it’s now possible to write one set of code that runs in both Internet Explorer and
Mozilla to handle parsing errors:
var oXmlDom = new XmlDom();
oXmlDom.onreadystatechange = function () {
if (oXmlDom.readyState == 4) {
if (oXmlDom.parseError != 0) {
var oError = oXmlDom.parseError;
alert(“An error occurred:\nError Code: “
+ oError.errorCode + “\n”
+ “Line: “ + oError.line + “\n”
+ “Line Pos: “ + oError.linepos + “\n”
+ “Reason: “ + oError.reason);
}
}
};
oXmlDom.load(“errors.xml”);
This example loads an XML file with errors in it. When the
readyState
property is set to
4
(the file is
loaded and parsed), the value of
parseError
is checked to see if it isn’t equal to zero (which indicates
an error). If an error has occurred, an alert is displayed with the error code, line number, line position
(column number), and reason for the error.
The complete code
In this chapter, I jumped around a lot as I developed the code. Here’s a look at the complete code (note
that it makes use of the browser detection code created earlier in the book):
function XmlDom() {
if (window.ActiveXObject) {
var arrSignatures = [“MSXML2.DOMDocument.5.0”, “MSXML2.DOMDocument.4.0”,
“MSXML2.DOMDocument.3.0”, “MSXML2.DOMDocument”,
“Microsoft.XmlDom”];
for (var i=0; i < arrSignatures.length; i++) {
try {
var oXmlDom = new ActiveXObject(arrSignatures[i]);
return oXmlDom;
} catch (oError) {
//ignore
}
}
throw new Error(“MSXML is not installed on your system.”);
} else if (document.implementation && document.implementation.createDocument) {
463
XML in JavaScript
18_579088 ch15.qxd 3/28/05 11:42 AM Page 463
Free JavaScript Editor
Ajax Editor
©
→