18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15<br />

Because the xml property needs to be available on every type of node in a document, it’s best to add it to<br />

the Node class itself (remember, all other node types inherit from Node):<br />

Node.prototype.__defineGetter__(“xml”, function () {<br />

var oSerializer = new XMLSerializer();<br />

return oSerializer.serializeToString(this, “text/xml”);<br />

});<br />

The function assigned to the xml property is very simple, and the only change from the earlier example<br />

is that this is the first argument for the serializeToString() method (remember, in this context<br />

this refers to the node). If you include this code in a page, it’s possible to use this custom xml property<br />

in the same manner as Microsoft’s xml property:<br />

oXmlDom.load(“test.xml”);<br />

alert(oXmlDom.xml);<br />

var oNode = oXmlDom.documentElements.childNodes[1];<br />

alert(oNode.xml);<br />

This code must also be surrounded by a browser detect because it only works in<br />

Mozilla.<br />

Parsing errors<br />

When an error occurs in the parsing of an XML file, the XML DOM creates a document explaining the<br />

error. Suppose you ran the following code:<br />

var oParser = new DOMParser()<br />

var oXmlDom = oParser.parseFromString(“”);<br />

Although no error is thrown, oXmlDom shows you the error. In this case, it presents this code:<br />

<br />

XML Parsing Error: not well-formed<br />

Location: file://c:/Chapter 15/examples/MozillaXmlDomExample.htm<br />

Line Number 5, Column 1:&lt;root&gt;&lt;child&gt;&lt;/root&gt;<br />

--------------^<br />

<br />

So to determine if there’s an error in the parsing of XML code, you must test the tag name of the document<br />

element:<br />

if (oXmlDom.documentElement.tagName != “parsererror”) {<br />

//continue on, no errors<br />

} else {<br />

//do something else, there was an error<br />

}<br />

454

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!