2013-10-28 32 views
0

我一直在为许多教程,我似乎仍然无法得到这个权利。Xml和Javascript

我有下面的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> 

    <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">Learning XML</title> 
    <author>Erik T. Ray</author> 
    <year>2003</year> 
    <price>39.95</price> 
    </book> 

</bookstore> 

我也有如下因素的javascript在我的HTML

if (window.XMLHttpRequest) 
    { 
    xhttp=new XMLHttpRequest(); 
    } 
else // for IE 5/6 
    { 
    xhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xhttp.open("GET","book.xml",false); 
xhttp.send(); 
xmlDoc=xhttp.responseXML; 

alert(xmlDoc.getElementsByTagName("title").nodeValue); 

我希望能够提醒特定标题(或所有标题如果可能的话) 。

这怎么可能?

+0

如果您登录'xmlDoc'到_console_您能得到什么? –

+0

getElementsByTagName返回节点列表,不能在列表上使用nodeValue。 – epascarello

+0

正如epascarello所说,你必须遍历由'getElementsByTagName'返回的_NodeList_来查看单个_Nodes_。 –

回答

1

所以,我怎么能得到的只是第一个“称号”,并提醒呢?

假设xmlDoc

var titles = xmlDoc.getElementsByTagName("title"); // NodeList 
if (titles[0])     // if there is an item in index 0 
    alert(titles[0].textContent); // alert it's textContent 
else        // otherwise 
    alert('Error: no titles'); // some error message 
+0

其提醒null – craig

+0

@craig对不起,假设_nodeValue_是您想要的属性,请尝试使用_textContent_来代替(编辑)。 –

+0

完美现在非常感谢 – craig