2014-11-25 54 views
0

最簡單的示例w3c頁面在firefox中不起作用,但是如果它在Chrome中起作用。 選擇的XPath屬性:我無法在Firefox中使用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

不要使用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); 
 
    } 
 
}