2011-05-25 39 views
0

我有以下XML关于XML DOM

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<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">XQuery Kick Start</title> 
    <author>James McGovern</author> 
    <author>Per Bothner</author> 
    <author>Kurt Cagle</author> 
    <author>James Linn</author> 
    <author>Vaidyanathan Nagarajan</author> 
    <year>2003</year> 
    <price>49.99</price> 
    </book> 
<book category="web" cover="paperback"> 
    <title lang="en">Learning XML</title> 
    <author>Erik T. Ray</author> 
    <year>2003</year> 
    <price>39.95</price> 
    </book> 
    </bookstore> 

,现在我试图Ø通过下面的代码

<script type="text/javascript"> 
var doc=new ActiveXObject("Microsoft.XMLDOM"); 
doc.async="true"; 
doc.load("test.xml"); 
var x=doc.getElementsByTagName("title"); 
for(var i=0;i<x.length;i++) 
{ 
document.write(x[i].childNodes[i].nodeValue); 
} 
</script> 

获得通过JavaScript的元素,但这仅读取第一个元素,即“每天意大利“并且还显示错误

Message: Object required 
Line: 11 
Char: 1 
Code: 0 

任何帮助请在那里。

+0

您现在的ActiveXObject是老的IE浏览器,在这里阅读更多http://www.w3schools.com/xml/xml_http.asp – Ibu 2011-05-25 06:44:37

回答

1

由于每个标题只有1个节点,所以它应该是

<script type="text/javascript"> 
    var doc=new ActiveXObject("Microsoft.XMLDOM"); 
    doc.async="true"; 
    doc.load("test.xml"); 
    var x=doc.getElementsByTagName("title"); 
    for(var i=0;i<x.length;i++) 
    { 
    document.write(x[i].childNodes[0].nodeValue); // replace i with 0 in childNodes 
    } 
</script>