我正在做一个Phonegap应用程序,我想使用xml文件,即我想在xml中搜索特定节点。我使用的xml文件如下所示。
<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">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
在这里,我想搜索图书的类别并显示该图书的所有详细信息。如果我搜索类别&#34; web&#34;,它将返回具有类别&#34; web&的图书的详细信息#34;
提前致谢.....
答案 0 :(得分:0)
var xml = "<bookstore><book category='cooking'>aaaa</book></bookstore>";
var result = $(xml).find("book").text();
答案 1 :(得分:0)
如果您不想使用任何JavaScript库,可以试试这个:
<script type="text/javascript">
function loadXMLString(txt) {
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
return xmlDoc;
}
window.onload = function () {
text = '<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">Learning XML</title>'
+ '<author>Erik T. Ray</author>'
+ '<year>2003</year>'
+ '<price>39.95</price>'
+ '</book>'
+ '</bookstore>';
xmlDoc = loadXMLString(text);
x = xmlDoc.getElementsByTagName("book");
for (i = 0; i < x.length; i++) {
if (x[i].attributes["category"].value == "web") {
var message = "";
for (var j = 0; j < x[i].childNodes.length; j++) {
message += x[i].childNodes[j].nodeName + ':' + x[i].childNodes[j].textContent + '\n'
}
alert(message);
}
}
}
</script>