簡體   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