1
我在JavaScript中苦苦掙扎了一些XML,如何才能僅選擇具有某些屬性值的標記?如何通過標記屬性檢索XML標記
下面的示例w3 schools使用此xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<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 McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
然後將下面的腳本獲取並在新的一行打印出所有從價格標籤的文本。
<html>
<body>
<script type="text/javascript">
function loadXMLDoc(dname){
if (window.XMLHttpRequest){
xhttp=new XMLHttpRequest();
}
else{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
//getting the xml into a var to parse
xml=loadXMLDoc("books.xml");
//the path in question
path="/bookstore/book/price/text()" ////how can i change this to only select the prices of the books where the category="COOKING" ?
// code for IE
if (window.ActiveXObject){
var nodes=xml.selectNodes(path);
for (i=0;i<nodes.length;i++)
{
document.write(nodes[i].nodeValue);
document.write("<br />");
}
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument){
var nodes=xml.evaluate(path, xml, null, XPathResult.ANY_TYPE,null);
var result=nodes.iterateNext();
while (result)
{
document.write(result.nodeValue + "<br />");
result=nodes.iterateNext();
}
}
</script>
</body>
</html>
是否有可能改變路徑,這樣腳本將只打印價格標籤,其中父標籤「書」有「烹飪」的類別屬性的文本(我把評論腳本當前路徑是我認爲我需要改變的地方,但我無法知道如何)?
我真的陷入困境,似乎無法找到如何得到它。任何幫助將很棒:) :)