2013-01-17 34 views
0

打賭這真的很簡單,但我一直在努力幾個小時才能使它工作。expandable getElementsByTagName array

即時通訊使用javascript讀取XML文件,但我不能得到它讀取我的noods,只有當我更改索引(手動)在它讀取第二行的數組中。

這是我使用寫出來的線用

document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue); 

正如我說,當我改變(「名稱」)[0]至(「名稱」)[1]它讀取的行第二行。 有沒有辦法我可以創建一個循環?使用.length?

這是一些代碼。

document.write("<table border='1'>"); 
var x =xmlDoc.getElementsByTagName("products"); 
for (i=0;i<x.length;i++) 
    { 
    document.write("<tr><td>"); 
    document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue); 
    document.write("</td><td>"); 
    document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue); 
    document.write("</td><td>"); 
    document.write("</td></tr>"); 
    } 
document.write("</table>"); 

和XML文件

<productlist> 
<products> 
    <title>Kök</title> 
    <product><id>23</id><name>Bestick</name><price>45</price></product> 
    <product><id>47</id><name>Tallrikar</name><price>99</price></product> 
    <product><id>54</id><name>Glas</name><price>64</price></product> 
    <product><id>68</id><name>Koppar</name><price>125</price></product> 
</products> 
<products> 
    <title>Sängkläder</title> 
    <product><id>12</id><name>Lakan</name><price>89</price></product> 
    <product><id>43</id><name>Kudde</name><price>148</price></product> 
    <product><id>48</id><name>Täcke</name><price>345</price></product> 
</products> 
</productlist> 

感謝。

回答

1

你已經有一個循環,顯然你需要另一個問題:

document.write("<table border='1'>"); 
var x = xmlDoc.getElementsByTagName("products"); 
for (var i=0;i<x.length;i++) 
    { 
    document.write("<tr><td>"); 
    document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue); 
    document.write("</td><td>"); 
    // Get all names on current products node, and loop 
    var names = x[i].getElementsByTagName("name"); 
    for(var j=0; j<names.length; j++) { 
    document.write(names[j].childNodes[0].nodeValue); 
    } 
    document.write("</td><td>"); 
    document.write("</td></tr>"); 
    } 
document.write("</table>"); 
+0

哦,謝謝!我一直試圖讓它與循環工作,但不能正確。 再次感謝您。 – Dymond