Xml and Javascript

Xml and Javascript

本文关键字:Javascript and Xml      更新时间:2023-09-26

我已经看过很多教程了,但我似乎仍然无法做到这一点。

我有以下 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>

我的HTML中也有以下javascript

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);

我希望能够提醒特定标题(如果可能,则提醒所有标题)。

这怎么可能?

那么,如何才能只获得第一个"标题"并提醒它呢?

假设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