Simple Implementation of selectNodes() and selectSingleNode() for FireFox [Mozilla]
**UPDATE** Now WORKS FOR OPERA > v 9.0
FireFox [Mozilla] by default doesn't have selectNodes or selectSingleNode methods that Internet Explorer (IE) XMLDOM has. Parsing an XPath Expression to these methods will return a collection of Nodes or a single Node that match the XPath Expression. The following simple script will expand the XMLDocument and Element objects for Mozilla to enable these functions.
Download
Here is the current version of the script mozXPath.js ( 05/07/2009 v 1.9a )
Script
selectNodes()
// check for XPath implementation
if( document.implementation.hasFeature("XPath", "3.0") )
{
// prototying the XMLDocument
XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
{
if( !xNode ) { xNode = this; }
var oNSResolver = this.createNSResolver(this.documentElement)
var aItems = this.evaluate(cXPathString, xNode, oNSResolver,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
var aResult = [];
for( var i = 0; i < aItems.snapshotLength; i++)
{
aResult[i] = aItems.snapshotItem(i);
}
return aResult;
}
// prototying the Element
Element.prototype.selectNodes = function(cXPathString)
{
if(this.ownerDocument.selectNodes)
{
return this.ownerDocument.selectNodes(cXPathString, this);
}
else{throw "For XML Elements Only";}
}
}
selectSingleNode()
// check for XPath implementation
if( document.implementation.hasFeature("XPath", "3.0") )
{
// prototying the XMLDocument
XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
{
if( !xNode ) { xNode = this; }
var xItems = this.selectNodes(cXPathString, xNode);
if( xItems.length > 0 )
{
return xItems[0];
}
else
{
return null;
}
}
// prototying the Element
Element.prototype.selectSingleNode = function(cXPathString)
{
if(this.ownerDocument.selectSingleNode)
{
return this.ownerDocument.selectSingleNode(cXPathString, this);
}
else{throw "For XML Elements Only";}
}
}
Example
xml document
Concider the folliwing xml document:
Usage
Below is an example that uses both of the methods.
function test( oXML )
{
var xItems = oXML.responseXML.selectNodes( "//complex/node/test/text()");
var sn = "XPath : //complex/node/test/text() \nMethod : selectNodes()\n";
for( var i = 0; i < xItems.length; i++ )
{
sn += "index : "+ i + " | value : " + xItems[i].nodeValue + "\n";
}
alert( sn );
ssn = "XPath : //complex/node/test/text() \nMethod : selectSingleNode()\n";
ssn+= oXML.responseXML.selectSingleNode( "//complex/node/test/text()").nodeValue;
alert( ssn );
}
Opera Fix
It appears that Opera doesn't have the XMLDocument object type, and the oXml.responseXML is infact Document
if( typeof XMLDocument == "undefined" ){ XMLDocument = Document; }
Acknowledgements
The example script on this page makes use h3h'sXHConn XMLHttpRequest Libary to obtain xml from the server.
Thanks to #javascript (efnet) for help and support