↑
Main Page
XPathResult.ORDERED_NODE_ITERATOR_TYPE
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null);
var aNodes = new Array;
if (oResult != null) {
var oElement = oResult.iterateNext();
while(oElement) {
aNodes.push(oElement);
oElement = oResult.iterateNext();
}
}
return aNodes;
};
The
selectNodes()
method is added to the
Element
class to mimic the behavior in IE. When
evaluate()
is called, it uses the
this
keyword as the context node (which is also how IE works). Then, a result array
(
aNodes
) is filled with all the matching nodes. You can use this new method like so:
var aNodes = oXmlDom.documentElement.selectNodes(“employee/name”);
for (var i=0; i < aNodes.length; i++) {
alert(aNodes[i].xml);
}
If you specify a snapshot result type (either ordered or unordered), you must use the
snapshotItem()
and
snapshotLength()
methods, as in the following example:
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(“employee/name”, oXmlDom.documentElement, null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
if (oResult != null) {
for (var i=0; i < oResult.snapshotLength; i++) {
alert(oResult.snapshotItem(i).tagName);
}
}
In this example,
snapshotLength
returns the number of nodes in the snapshot and
snapshotItem()
returns the node in a given position in the snapshot (similar to
length
and
item()
in a
NodeList
).
The
XPathResult.FIRST_ORDERED_NODE_TYPE
result returns the first matching node, which is accessi-
ble through the
singleNodeValue
property:
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(“employee/name”, oXmlDom.documentElement, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null);
alert(oResult.singleNodeValue.xml);
As you may have guessed, this code can be used to mimic the IE
selectSingleNode()
method:
469
XML in JavaScript
18_579088 ch15.qxd 3/28/05 11:42 AM Page 469
Free JavaScript Editor
Ajax Editor
©
→