04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 15: XML in JavaScript<br />

To parse an XML string, you must first create a DOM document and then call the loadXML() method.<br />

When the document is first created, it is completely empty and so cannot be interacted with. Passing an<br />

XML string into loadXML() parses the XML into the DOM document. Here’s an example:<br />

var xmldom = createDocument();<br />

xmldom.loadXML(“ < root > < child/ > < /root > ”);<br />

alert(xmldom.documentElement.tagName); //”root”<br />

alert(xmldom.documentElement.firstChild.tagName); //”child”<br />

var anotherChild = xmldom.createElement(“child”);<br />

xmldom.documentElement.appendChild(anotherChild);<br />

var children = xmldom.getElementsByTagName(“child”);<br />

alert(children.length); //2<br />

Once the DOM document is filled with XML content, it can be interacted with just like any other DOM<br />

document, including all methods and properties.<br />

Parsing errors are represented by the parseError property, which is an object with several properties<br />

relating to any parsing issues. These properties are as follows:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

errorCode — Numeric code indicating the type of error that occurred or 0 when there ’ s no error<br />

filePos — Position within the file where the error occurred<br />

line — The line on which the error occurred<br />

linepos — The character on the line where the error occurred<br />

reason — A plain text explanation of the error<br />

srcText — The code that caused the error<br />

url — The URL of the file that caused the error (if available)<br />

The valueOf() method for parseError returns the value of errorCode , so you can check to see if a<br />

parsing error occurred by using the following:<br />

if (xmldom.parseError != 0){<br />

alert(“Parsing error occurred.”);<br />

}<br />

An error code maybe a positive or negative number, so you need only check to see if it ’ s not equal to 0.<br />

The details of the parsing error are easily accessible and can be used to indicate more useful error<br />

information, as shown in the following example:<br />

if (xmldom.parseError != 0){<br />

alert(“An error occurred:\nError Code: “<br />

+ xmldom.parseError.errorCode + “\n”<br />

+ “Line: “ + xmldom.parseError.line + “\n”<br />

+ “Line Pos: “ + xmldom.parseError.linepos + “\n”<br />

+ “Reason: “ + xmldom.parseError.reason);<br />

}<br />

525

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

Saved successfully!

Ooh no, something went wrong!