HTML-XML数据解析

HTML代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript">
window.onload = function () {
var xhr = null;
if (window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("get", "Book.xml", true);
xhr.send(null);
xhr.onreadystatechange = function (data) {
if (xhr.readyState==4) {
if (xhr.status == 200) {
var data = xhr.responseXML;
var bs = data.getElementsByTagName("bookstore")[0];
var books = bs.getElementsByTagName("book");
var li="";
for (var i = 0; i < books.length; i++) {
var book = books[i];
var name = book.getElementsByTagName("name")[0];
var person = book.getElementsByTagName("person")[0];
var like = book.getElementsByTagName("like")[0];
li+='<li>'+getNodeText(name)+'<br/>'+getNodeText(person)+'<br/>'+getNodeText(like)+'<br/></li>'
}
var ul = document.createElement("ul");
ul.innerHTML = li;
document.getElementById("book").appendChild(ul);
}
}
}
}
function getNodeText(node) {
if (window.ActiveXObject) {
return node.text;
} else {
if (node.nodeType==1) {
return node.textContent;
}
}
}
</script>
</head>
<body>
<div id="book"></div>
</body>
</html>

XML数据

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book>
<name>三生三世十里桃花</name>
<person>杨幂</person>
<like>yes</like>
</book>
<book>
<name>楚乔传</name>
<person>赵丽颖</person>
<like>yes</like>
</book>
<book>
<name>花千骨</name>
<person>赵丽颖</person>
<like>yes</like>
</book>
</bookstore>

运行结果:

HTML-XML数据解析

上一篇:UFLDL 教程学习笔记(四)主成分分析


下一篇:『Golang』Go简介以及环境搭建