我在使用javascript中的某些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>
是否可以更改路径,以便脚本只打印出价格标签的文本,其中父标签'book'的类别属性为'COOKING'(我在脚本中放置当前路径的注释)是我认为我需要改变,但我不知道如何改变??
我真的被卡住了,似乎无法找到如何获得它。任何帮助都会很棒:)
答案 0 :(得分:3)
在你的路径中你需要放置//bookName/[@CATEGORY = COOKING]
@是它查看属性的地方。希望这会有所帮助。