books.xml文件
<?xml version="1.0" encoding="utf-8"?> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">XQuery Kick Start</title> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="WEB"> <title lang="zh">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
test.html文件
<html> <head> <title>xpath test</title> <mce:script type="text/javascript"><!-- var xmlDoc ; var exploer; loadXML(); //载入Xml文档 function loadXML(){ // IE 浏览器 if (window.ActiveXObject) { exploer='ie'; xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async= false; xmlDoc.load("books.xml"); } // Mozilla, Firefox, Opera浏览器 else if (document.implementation &&document.implementation.createDocument){ exploer='firefox'; xmlDoc = document.implementation.createDocument("","",null); xmlDoc.load("books.xml"); } else{ alert("由于你的浏览器不支持Javascript,目录树无法加载..."); } } function fnIEParse(path){ alert(path); var nodes = xmlDoc.selectNodes(path); for(var i=0;i<nodes.length;i++){ var node = nodes[i]; alert(node.xml); } } function fnFirefoxParse(path){ alert(path); var oNSResolver = xmlDoc.createNSResolver(xmlDoc.documentElement); var nodes = xmlDoc.evaluate(xpath,xmlDoc, oNSResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); alert(""); } function fnSelectNodes(){ var path=document.getElementById("path").value; if(exploer=='ie'){ fnIEParse(path); }else if(exploer='firefox'){ fnFirefoxParse(path); }else{ alert("由于你的浏览器不支持Javascript,path..."); } } // --></mce:script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head> <body> 输入xpath eg://book[title[@lang='en'] and price<=30]/title/text() <br> <input type="text" id="path" size="120"/> <input type="button" value="get nodes" onclick="fnSelectNodes()"/> <br> <div id="books"> <iframe src="books.xml" mce_src="books.xml" width="100%" height="90%"></iframe> </div> </body> </html>
两个文件放在同一个目录下即可。
运行test.html,输入
//book[title[@lang='en'] and price<=30]/title/text()
快看看效果吧!
输入这个呢?
/bookstore/book/year[.=2005]