↑
Main Page
XPathEvaluator
Element.prototype.selectSingleNode = function (sXPath) {
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(sXPath, this, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null);
if (oResult != null) {
return oResult.singleNodeValue;
} else {
return null;
}
}
This method can then be used the same as the one in IE:
var oNode = oXmlDom.documentElement.selectSingleNode(“employee/name”);
alert(oNode);
The last section of
XPathResult
types are the Boolean type, number type, and string type. Each of these
result types returns a single value using the
booleanValue
,
numberValue
, and
stringValue
proper-
ties, respectively. For the Boolean type, the evaluation typically returns
true
if at least one node matches
the XPath expression and returns
false
otherwise:
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(“employee/name”, oXmlDom.documentElement, null,
XPathResult.BOOLEAN_TYPE, null);
alert(oResult.booleanValue);
In this example, if any nodes match
“employee/name”
, the
booleanValue
property is equal to
true
.
For the number type, the XPath expression must use an XPath function that returns a number, such as
count()
, which counts all the nodes that match a given pattern:
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(“count(employee/name)”, oXmlDom.documentElement,
null, XPathResult.BOOLEAN_TYPE, null);
alert(oResult.numberValue);
This code outputs the number of nodes that match
“employee/name”
(which is 2). If you try using this
method without one of the special XPath functions,
numberValue
is equal to
NaN
.
For the string type, the
evaluate()
method finds the first node matching the XPath expression, then
returns the value of the first child node, assuming the first child node is a text node. If not, the result is
an empty string. Here’s an example:
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(“employee/name”, oXmlDom.documentElement, null,
XPathResult.STRING_TYPE, null);
alert(oResult.stringValue);
The previous code outputs
“Nicholas C. Zakas”
, because that is the first text node in the first
<name/>
element under an
<employee/>
element.
470
Chapter 15
18_579088 ch15.qxd 3/28/05 11:42 AM Page 470
Free JavaScript Editor
Ajax Editor
©
→