在项目下新建一个xpath.html 文件,编写代码解析books.xml。
代码如下:
Title/*定义一个函数用来加载xml文档*/
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();//获取XMLHttpRequest对象
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
xml = loadXMLDoc("books.xml");
/*
信息的位置
path = "/bookstore/book/title"//选取所有title还可以这样写:path="//title[@lang='en']"
path="/bookstore/book[1]/title" //选取第一个 book 的 title
path ="/bookstore/book/price/text()" //选取所有价格
path = "/bookstore/book[price>35]/price" //选取价格高于 35 的 price 节点
path = "//author" //选取作者
path = "//year" //选取年份
*/
path = "//price";
if(window.ActiveXObject){
/*xmlDoc.selectNodes(xpath);从XML文档中选取节点*/
var nodes = xml.selectNodes(path);
for (i = 0; i
document.write(nodes[i].childNodes[0].nodeValue);
document.write("
");
}
} else if (document.implementation && document.implementation.createDocument) {
/*Firefox、Chrome、Opera 以及 Safari 使用 evaluate() 方法从 XML 文档中选取节点:*/
var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
var result = nodes.iterateNext();
while (result) {
document.write(result.childNodes[0].nodeValue);
//document.write(result.nodeValue); //选取所有价格对应的处理
document.write("
");
result = nodes.iterateNext();
}
}