我编写了以下代码来读取XML文件并显示它,但它不起作用。
谁能告诉我哪里出错了?尝试加载并显示 XML:
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "books.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
var tbl = document.createElement("table");
tbl.className = "datatable";
tbl.border = "6";
tbl.width = "500";
tbl.cellPadding = "10";
var tbody = document.createElement("tbody");
var x = xmlDoc.getElementsByTagName("Book");
for (i = 0; i < x.length; i++) {
var title = x[i].childNodes[0].text;
var author = x[i].childNodes[1].text;
//var title = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
//var author = x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;
var row = document.createElement("tr");
var td = document.createElement("td");
td.appendChild(title);
//td.appendChild(author);
row.appendChild(td);
}
tbody.appendChild(row);
tbl.appendChild(tbody);
document.getElementById("content").appendChild(tbl);
<?xml version="1.0" encoding="utf-8"?>
<Books>
<Book>
<title>A Bend in the river</title>
<author>V.S. Naipaul</author>
</Book>
<Book>
<title>Earth</title>
<author>Emile Zola</author>
</Book>
<Book>
<title>I am not an Island</title>
<author>V.S. Naipaul</author>
</Book>
<Book>
<title>Macbeth</title>
<author>William Shakespeare</author>
</Book>
<Book>
<title>Quarantene</title>
<author>Jim Crass</author>
</Book>
</Books>
感谢任何能提供帮助的人。