html5读取xml实例
时间: 2023-08-22 15:05:50 浏览: 52
以下是一个简单的 HTML5 代码示例,用于使用 XMLHttpRequest 对象读取 XML 文件:
```html
<!DOCTYPE html>
<html>
<head>
<title>读取 XML 文件</title>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">加载 XML 文件</button>
<br><br>
<table id="demo"></table>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
displayResult(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
}
function displayResult(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Title</th><th>Author</th></tr>";
var x = xmlDoc.getElementsByTagName("book");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
```
此代码使用了 XMLHttpRequest 对象来获取 XML 文件,然后通过 `getElementsByTagName()` 方法和节点的名称来获取 XML 文件中的数据,最后将数据显示在 HTML 表格中。请注意,这仅是一个简单的示例,您需要根据自己的需求进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)