Main Page

XPath support in IE

XPath support in IE
Microsoft saw fit to build XPath support right into the XML DOM object. Each node has two methods
that can be used to retrieve nodes matching an XPath pattern:
selectNodes()
, which returns a collec-
tion of nodes matching a pattern, and
selectSingleNode()
, which returns the first node that matches
a given pattern.
Using the same data as the previous section, you can select all
<name/>
elements that are children of an
<employee/>
element by using the following code:
var lstNodes = oXmlDom.documentElement.selectNodes(“employee/name”);
Because
selectNodes()
is called as a method of
oXmlDom.documentElement
, the document element
is considered the context node for the XPath expression. The method returns a
NodeList
containing all
elements that match the given pattern, meaning that you can iterate through the elements like so:
for (var i=0; i < lstNodes.length; i++) {
alert(lstNodes[i]);
}
Even if there are no matches to a given pattern, a
NodeList
is still returned. If it is empty, its
length
property is equal to
0
.
If you want only the first element matching the pattern, then
selectSingleNode()
is the method to use:
var oElement = oXmlDom.documentElement.selectSingleNode(“employee/name”);
The
selectSingleNode()
method returns an
Element
as the function value if found, otherwise it
returns
null
.
XPath support in Mozilla
As you may have guessed, Mozilla supports the XPath according to the DOM standard. A DOM Level 3
addition called DOM Level 3 XPath defines interfaces to use for evaluating XPath expressions in the
DOM. Unfortunately, this standard is more complicated than Microsoft’s fairly straightforward
approach.
Although a handful of XPath-related objects exist, the two most important ones are
XPathEvaluator
and
XPathResult
. An
XPathEvaluator
is used to evaluate an XPath expression with a method named,
appropriately enough,
evaluate()
.
The
evaluate()
method takes five arguments: the XPath expression, the context node, a namespace
resolver, the type of result to return, and an
XPathResult
object to fill with the result (usually
null
).
The result of
selectNodes()
is a living list. So, if you update the document with
another element that matches the XPath expression, that element is automatically
added to the
NodeList
in the appropriate position.
467
XML in JavaScript
18_579088 ch15.qxd 3/28/05 11:42 AM Page 467


JavaScript EditorFree JavaScript Editor     Ajax Editor


©