我已經經歷了xml中的基礎知識,現在嘗試使用javascript解析xml數據。 我已經從w3schools &獲得了幫助,編寫了下面的代碼,但沒有發生解析,並且顯示了一個空白頁面。請幫助...使用Javascript解析XML數據
的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>
除非你出於學術好奇,否則你最好使用預先編寫的庫,比如jQuery。請點擊此處:https://api.jquery.com/jQuery.parseXML/ –
請勿使用'document.write',請參閱[規範]中的警告(http://www.w3.org/TR/html5 /dom.html#document.write%28%29)。改用DOM方法。 – Oriol
是你的'xmlDoc'一個XML對象嗎?做一個'console.log(xmlLog);'確定。 – Ibu