jquery解析xml
jquery解析xml一、jquery解析xml步骤
1、获取XML
$(document).ready(function() {
$.ajax({
url: '/xml/books。xml',
type: 'GET',
dataType: 'xml',
timeout: 1000, //设定超时
cache: false, //禁用缓存
error: function(xml) {
alert("加载XML文档出错!");
},
success: GetStudentComplete //设置成功后回调函数
});
});
2、解析XML
//获取XML成功后回调函数
function GetStudentComplete(xml) {
$(xml).find("student").each(function(i) { //查找所有student节点并遍历
var id = $(this).children("id"); //获得子节点
var id_vaule = id.text(); //获取节点文本
var email_vaule = $(this).attr("email"); //获取节点的属性
alert(id_vaule);
alert(email_vaule);
});
}
二、jquery解析xml完整实例
1、xml文件结构:books。xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<book id="1">
<name>深入浅出extjs</name>
<author>张三</author>
<price>88</price>
</book>
<book id="2">
<name>锋利的jQuery</name>
<author>李四</author>
<price>99</price>
</book>
<book id="3">
<name>深入浅出flex</name>
<author>王五</author>
<price>108</price>
</book>
<book id="4">
<name>java编程思想</name>
<author>钱七</author>
<price>128</price>
</book>
</root>
2、页面代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jquery解析xml</title>
<script type="text/javascript" src="js/jquery-1.7.min。js"></script>
<script type="text/javascript">
$(function(){
$.post('books.xml',function(data){
//查找所有的book节点
var s="";
$(data).find('book').each(function(i){
var id=$(this).attr('id');
var name=$(this).children('name').text();
var author=$(this).children('author').text();
var price=$(this).children('price').text();
s+=id+" "+name+" "+author+" "+price+"<br>";
});
$('#myli').html(s);
});
});
</script>
</head>
<body>
<li id='myli'></li>
</body>
</html>
3、效果图