最简单的示例w3c页面在Firefox中不起作用,但如果它在Chrome中有效。 选择xpath属性:
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>
</bookstore>
HTML:
<!DOCTYPE html>
<html>
<body>
<script>
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
try {xhttp.responseType="msxml-document"} catch(err) {} // Helping IE
xhttp.send("");
return xhttp;
}
var x=loadXMLDoc("books.xml");
var xml=x.responseXML;
path="/bookstore/book/title/lang/@lang";
// code for IE
if (window.ActiveXObject || xhttp.responseType=="msxml-document")
{
xml.setProperty("SelectionLanguage","XPath");
nodes=xml.selectNodes(path);
for (i=0;i<nodes.length;i++)
{
document.write(nodes[i].childNodes[0].nodeValue);
document.write("<br>");
}
}
// code for Chrome, 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.childNodes[0].nodeValue);
document.write("<br>");
result=nodes.iterateNext();
}
}
</script>
</body>
</html>
您可以看到Xpath表达式:
path="/bookstore/book/title/lang/@lang"
我无法在Firefox中使用它,但如果它适用于Google Chrome,Opera和Internet Explorer。
答案 0 :(得分:0)
不要使用if (document.implementation && document.implementation.createDocument)
作为检查来使用evaluate
方法,如果您想使用某种方法,请检查该方法,而不是其他不相关的对象。
所以检查
if (typeof xml.evaluate != 'undefined') {
var xpathResult = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
var node;
wile ((node = xpathResult.iterateNext()) != null) {
document.write(node.nodeValue);
}
}
应该这样做。你的XPath选择属性节点,所以只需访问该属性的nodeValue,我不明白为什么你认为它有一个子节点可以访问。
var xmlSource = [
'<bookstore>',
'<book category="COOKING">',
'<title lang="en">Everyday Italian</title>',
'<author>Giada De Laurentiis</author>',
'<year>2005</year>',
'<price>30.00</price>',
'</book>',
'</bookstore>'
].join('\n');
var xmlDoc;
if (typeof DOMParser != 'undefined') {
xmlDoc = new DOMParser().parseFromString(xmlSource, 'application/xml');
}
var path="/bookstore/book/title/@lang";
if (typeof xmlDoc.evaluate != 'undefined') {
var xpathResult = xmlDoc.evaluate(path, xmlDoc, null, XPathResult.ANY_TYPE, null);
var node;
while ((node = xpathResult.iterateNext()) != null) {
console.log(node.nodeValue);
}
}