Firefox默认不支持IE的XMLDOM提供的selectNodes和selectSingleNode方法。IE中可以通过这两个方法解析获得一系列Nodes或者一个单独的Node。下面的脚本可以扩展Firefox的XMLDocument和Element对象以支持这两个函数。

代码

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

示例用文档:

<![CDATA[
<root>
<complex>
<node>
<test>value 1</test>
</node>
</complex>
<complex>
<node>
<test>value 2</test>
</node>
</complex>
<complex>
<node>
<test>value 3</test>
</node>
</complex>
<complex>
<node>
<test>value 4</test>
</node>
</complex>
</root> ]]>

用法示例

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 ); }
原文链接:http://km0ti0n.blunted.co.uk/mozXPath.xap