2012-12-31 216 views
0

我一直在使用xpath來瀏覽我的xml文檔,但是我從iterateNext()返回的值爲null的w3學校的示例如下。以下是我的blog.xml文件。document.evaluate返回null與iterateNext

<blog 
xmlns ="http://www.w3schools.com" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="blogschema.xsd"> 
<Title>My blog</Title> 

<Entry> 
    <Heading id="101">week1</Heading> 
    <body> 
     <text>enter text right here</text> 
     <pictures>pictures in the body</pictures> 

    </body> 
    <labels>Seperate labels with commas</labels> 
    <date> 20121119</date> 

</Entry> 





</blog> 

這是我的HTML腳本,永遠達不到while語句的結果總是返回null,,即時通訊俯瞰這也許東西,但我認爲,如果是在W3學校應該真正發揮作用。

xmlDoc=loadXMLDoc("blog.xml");//loads xml file 
//loadXmlContent(xmlDoc); using xml dom 

path="/blog/Title" 
if(document.implementation && document.implementation.createDocument) 
{ 

    var nodes = xmlDoc.evaluate(path, xmlDoc, null, 5, null); 
    alert(nodes); 
    var result = nodes.iterateNext(); 


    while (result) 
    {document.write(result.childNodes[0].nodeValue);} 

} 
</script> 
+1

我建議以下內容的[更好源(https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript)比[W3Schools的](http://w3fools.com/)。 – jbabey

回答

2

有一個默認命名空間聲明xmlns="http://www.w3schools.com"輸入,你需要考慮到與例如

var nodes = xmlDoc.evaluate("df:blog/df:Title", xmlDoc, function(prefix) { if (prefix === "df") return "http://www.w3schools.com"; }, 5, null); 

var result; 

while ((result = nodes.iterateNext()) != null) 
{ 
    document.write(result.textContent); 
} 
+0

謝謝,這似乎工作,但似乎除了博客和標題,例如標題@Martin Honnen以外別無其他 –