jquery解析XML文件
html代码
<!DOCTYPE html>
<html>
<head>
<title>解析XML</title>
<meta charset='utf-8' />
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="book">
</div>
</body>
</html>
css代码
<style type="text/css">
#book{
position: relative;
border: 1px green solid;
width: 200px;
}
#book .book{
position: relative;
border: 2px #aaa solid;
}
#book .name{
position: relative;
background-color: #999;
color: #fff;
}
#book .title{
border-bottom: 1px #999 solid;
}
book .content{
position: relative;
word-break:break-all;
word-wrap:break-all;
}
</style>
js代码
<script type="text/javascript">
$.get('book.xml',function(xml){
var len = $(xml).find('book').length;
$(xml).find("book").each(function() {
var book = $(this);
for (var i = 0; i < book.length; i++) {
var name = book.attr("name");//读取节点属性
var title = book.find("title").text();//读取子节点的值
var content = book.find("content").text();
var html = '<div class="book">';
html += '<div class="name">'+name+'</div>';
html += '<div class="title">'+title+'</div>';
html += '<div class="content">'+content+'</div>';
var content = book.find("content").text();
$('#book').append(html);
};
});
});
</script>
XML文件 book.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book name="MongoDB">
<title>MongoDB</title>
<content>MongoDBMongoDBMongoDBMongoDBMongoDBMongoDBMongoDBMongoDB</content>
</book>
<book name="Nodejs">
<title>Nodejs</title>
<content>MongoDBMongoDBMongoDBMongoDBMongoDBMongoDBMongoDBMongoDB</content>
</book>
<book name="Bootstrap">
<title>Bootstrap</title>
<content>MongoDBMongoDBMongoDBMongoDBMongoDBMongoDBMongoDBMongoDB</content>
</book>
<book name="JavaScript">
<title>JavaScript</title>
<content>JavaScriptJavaScriptJavaScriptJavaScriptJavaScript</content>
</book>
</books>