Main Page

Parsing errors

Because the
xml
property needs to be available on every type of node in a document, it’s best to add it to
the
Node
class itself (remember, all other node types inherit from
Node
):
Node.prototype.__defineGetter__(“xml”, function () {
var oSerializer = new XMLSerializer();
return oSerializer.serializeToString(this, “text/xml”);
});
The function assigned to the
xml
property is very simple, and the only change from the earlier example
is that
this
is the first argument for the
serializeToString()
method (remember, in this context
this
refers to the node). If you include this code in a page, it’s possible to use this custom
xml
property
in the same manner as Microsoft’s
xml
property:
oXmlDom.load(“test.xml”);
alert(oXmlDom.xml);
var oNode = oXmlDom.documentElements.childNodes[1];
alert(oNode.xml);
Parsing errors
When an error occurs in the parsing of an XML file, the XML DOM creates a document explaining the
error. Suppose you ran the following code:
var oParser = new DOMParser()
var oXmlDom = oParser.parseFromString(“<root><child></root>”);
Although no error is thrown,
oXmlDom
shows you the error. In this case, it presents this code:
<parsererror xmlns=”http://www.mozilla.org/newlayout/xml/parsererror.xml”>
XML Parsing Error: not well-formed
Location: file://c:/Chapter 15/examples/MozillaXmlDomExample.htm
Line Number 5, Column 1:<sourcetext>&lt;root&gt;&lt;child&gt;&lt;/root&gt;
--------------^</sourcetext>
</parsererror>
So to determine if there’s an error in the parsing of XML code, you must test the tag name of the docu-
ment element:
if (oXmlDom.documentElement.tagName != “parsererror”) {
//continue on, no errors
} else {
//do something else, there was an error
}
This code must also be surrounded by a browser detect because it only works in
Mozilla.
454
Chapter 15
18_579088 ch15.qxd 3/28/05 11:42 AM Page 454


JavaScript EditorFree JavaScript Editor     Ajax Editor


©