繁体   English   中英

使用Javascript解析XML数据

[英]Parsing XML data using Javascript

我已经了解了xml的基础知识,现在尝试使用javascript解析xml数据。 我从w3schools获得了帮助,并编写了以下代码,但没有进行解析,并且显示空白页。 请帮忙...

正在使用的xml文件是books.xml

<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>
</bookstore>

HTML代码是:

<!DOCTYPE html>
<html>
<head>
<script>

function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }

xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}


</script>
</head>
<body>
<script>

var xmlDoc=loadXMLDoc("C:/Users/A/Desktop/books.xml");

document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br>");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);


</script>

</body>

</html>

我已经尝试过您的代码,并且可以正常工作(我在Mac OSX上使用Mozilla Firefox 28)。

请记住,在Windows系统上,目录分隔符是反斜杠\\而不是斜杠/尝试在xml路径中更改它。 可能会看到一个空白页,因为您没有提供后备,以防ajax请求找不到该xml。 如果您使用的是Firebug,则在尝试获取该xml时应该会看到“ 404 Not Found”错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM