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.

XPath support in IE<br />

Microsoft saw fit to build XPath support right into the XML DOM object. Each node has two methods<br />

that can be used to retrieve nodes matching an XPath pattern: selectNodes(), which returns a collection<br />

of nodes matching a pattern, and selectSingleNode(), which returns the first node that matches<br />

a given pattern.<br />

Using the same data as the previous section, you can select all elements that are children of an<br />

element by using the following code:<br />

var lstNodes = oXmlDom.documentElement.selectNodes(“employee/name”);<br />

Because selectNodes() is called as a method of oXmlDom.documentElement, the document element<br />

is considered the context node for the XPath expression. The method returns a NodeList containing all<br />

elements that match the given pattern, meaning that you can iterate through the elements like so:<br />

for (var i=0; i < lstNodes.length; i++) {<br />

alert(lstNodes[i]);<br />

}<br />

XML in <strong>JavaScript</strong><br />

Even if there are no matches to a given pattern, a NodeList is still returned. If it is empty, its length<br />

property is equal to 0.<br />

The result of selectNodes() is a living list. So, if you update the document with<br />

another element that matches the XPath expression, that element is automatically<br />

added to the NodeList in the appropriate position.<br />

If you want only the first element matching the pattern, then selectSingleNode() is the method to use:<br />

var oElement = oXmlDom.documentElement.selectSingleNode(“employee/name”);<br />

The selectSingleNode() method returns an Element as the function value if found, otherwise it<br />

returns null.<br />

XPath support in Mozilla<br />

As you may have guessed, Mozilla supports the XPath according to the DOM standard. A DOM Level 3<br />

addition called DOM Level 3 XPath defines interfaces to use for evaluating XPath expressions in the<br />

DOM. Unfortunately, this standard is more complicated than Microsoft’s fairly straightforward<br />

approach.<br />

Although a handful of XPath-related objects exist, the two most important ones are XPathEvaluator<br />

and XPathResult. An XPathEvaluator is used to evaluate an XPath expression with a method named,<br />

appropriately enough, evaluate().<br />

The evaluate() method takes five arguments: the XPath expression, the context node, a namespace<br />

resolver, the type of result to return, and an XPathResult object to fill with the result (usually null).<br />

467

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

Saved successfully!

Ooh no, something went wrong!