Neil Zanella wrote:
> I would like to know whether the mozilla web browser has built in support
> for searching XML documents via XPath expressions as with IE's xmlobject's
> and xmlDoc's function selectNodes() or similar.
Mozilla has XPath support but not the restricted MSXML selectNodes but
rather a more complete approach that is being under development, Mozilla
attempts to implement the W3C DOM Level 3 XPath module:
http://www.w3.org/TR/2003/CR-DOM-Lev...Path-20030331/
At the heart of that is method
document.evaluate(
string xpathexpression,
node contextNode,
XPathNSResolver namespaceresolver,
number desiredResultType,
object resultObject
)
Some examples on how to use it, lets create a short example document first:
var xmlSource = '';
xmlSource += '<gods>';
xmlSource += '<god name="Kibo" />';
xmlSource += '<god name="Xibo" />';
xmlSource += '<\/gods>';
var xmlDocument = new DOMParser().parseFromString(xmlSource, 'text/xml');
var xmlSerializer = new XMLSerializer();
Selecting a single node:
var xpathResult = xmlDocument.evaluate(
'//god',
xmlDocument,
null,
9,
null
);
if (xpathResult.singleNodeValue) {
alert(xmlSerializer.serializeToString(xpathResult. singleNodeValue));
}
Selecting an ordered node list:
var xpathResult = xmlDocument.evaluate(
'//god',
xmlDocument,
null,
5,
null
);
var resultNode;
while ((resultNode = xpathResult.iterateNext())) {
alert(xmlSerializer.serializeToString(resultNode)) ;
}
Evaluating an expression that returns a number:
var xpathResult = xmlDocument.evaluate(
'count(//*/@*)',
xmlDocument,
null,
0,
null
);
if (xpathResult.resultType == 1) {
alert('Counted ' + xpathResult.numberValue + ' nodes.');
}
That should help you to get started if you then have a look at the
specification.
Or ask here if you have further questions.
There is even some attempt to extend XPath to HTML documents:
<html>
<head>
<title>"XPath" on HTML in Mozilla</title>
<script type="text/javascript">
function countCenteredParagraphs () {
if (typeof document.evaluate != 'undefined') {
var xpathResult =
document.evaluate(
'count(//p[@align = "center"])',
document,
null,
1,
null
);
alert('Found ' + xpathResult.numberValue + ' centered paragraphs.');
}
}
window.onload = countCenteredParagraphs;
</script>
</head>
<body>
<p align="center">
A paragraph with centered text.
</p>
<p align="center">
A second paragraph with centered text.
</p>
</body>
</html>
--
Martin Honnen
http://JavaScript.FAQTs.com/