↑
Main Page
XPathResult
The third argument, the namespace resolver, is necessary only when the XML code uses an XML names-
pace, and so typically is left as
null
. The fourth argument, the type of result to return, is one of 10 con-
stants values:
?
XPathResult.ANY_TYPE
— Returns the type of data appropriate for the XPath expression
?
XPathResult.ANY_UNORDERED_NODE_TYPE
— Returns a node set of matching nodes,
although the order may not match the order of the nodes within the document
?
XPathResult.BOOLEAN_TYPE
— Returns a Boolean value
?
XPathResult.FIRST_ORDERED_NODE_TYPE
— Returns a node set with only one node, which
is the first matching node in the document
?
XPathResult.NUMBER_TYPE
— Returns a number value
?
XPathResult.ORDERED_NODE_ITERATOR_TYPE
— Returns a node set of matching nodes in
the order in which they appear in the document. This is the most commonly used result type.
?
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE
— Returns a
node set snapshot
, capturing the
nodes outside of the document so that any further document modification doesn’t affect the
node list. The nodes in the node set are in the same order as they appear in the document.
?
XPathResult.STRING_TYPE
— Returns a string value
?
XPathResult.UNORDERED_NODE_ITERATOR_TYPE
— Returns a node set of matching nodes,
although the order may not match the order of the nodes within the document
?
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE
— Returns a node set snapshot, capturing the
nodes outside of the document so that any further document modification doesn’t affect the node
set. The nodes in the node set are not necessarily in the same order as they appear in the document.
The type of result you specify determines how to retrieve the value of the result. Here’s a typical example:
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(“employee/name”, oXmlDom.documentElement, null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
if (oResult != null) {
var oElement = oResult.iterateNext();
while(oElement) {
alert(oElement.tagName);
oElement = oResult.iterateNext();
}
}
This example uses the
XPathResult.ORDERED_NODE_ITERATOR_TYPE
result, which is the most com-
monly used result type. If no nodes match the XPath expression,
evaluate()
returns
null
; otherwise, it
returns an
XPathResult
object. If the result is a node iterator, whether it be ordered or unordered, you
use the
iterateNext()
method repeatedly to retrieve each matching node in the result. When there are
no further matching nodes,
iterateNext()
returns
null
. Using a node iterator, it’s possible to create a
selectNodes()
method for Mozilla:
Element.prototype.selectNodes = function (sXPath) [
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(sXPath, this, null,
468
Chapter 15
18_579088 ch15.qxd 3/28/05 11:42 AM Page 468
Free JavaScript Editor
Ajax Editor
©
→