jQuery这个语言做的最好的就是处理xml
(Extensible Markup Language
),下面直接上代码
<?xml version="1.0" encoding="utf-8" ?>
<!--test.xml-->
<school>
<student id="1" age="14">
<name>张三</name>
<email>zhangsan@csdn.net</email>
</student>
<student id="2" age="16">
<name>李四</name>
<email>lisi@csdn.net</email>
<phone>12345678900</phone>
</student>
<teacher age="31">
<name>王五</name>
<phone>98765432100</phone>
</teacher>
</school>
<!--test.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>xml解析测试</title>
<link rel='stylesheet' href='test.css' type='text/css'>
<script src='/jquery.js'></script>
<script src='test.js'></script>
</head>
<body>
<div id='middle'>
<table border='1'>
<tr>
<th>身份</th>
<th>名字</th>
<th>职业</th>
<th>年龄</th>
<th>邮箱</th>
<th>手机</th>
</tr>
</table>
</div>
</body>
</html>
/*test.css*/
* {
margin: 0 auto;
padding: 0;
font: inherit;
}
html,body {
width: 100%;
height: 100%;
font: 25px 'Consolas','Kaiti';
}
#middle {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
table {
border-collapse: collapse;
}
table,th {
border: 1px solid black;
}
table tr:nth-child(odd) {
background-color: #66EE66;
}
table tr:nth-child(even) {
background-color: #AAEEAA;
}
table tr:first-child {
background-color: #00FF00;
}
th {
padding: 5px;
text-align: center;
}
//test.js
$(function(){
'use strict';
$.ajax({
url: 'test.xml',
type: 'POST',
dataType: 'xml',
success: function(xml){
$(xml).find('student').each(function(){
$('<tr></tr>').append('<th>'+$(this).attr('id')+'</th>')
.append('<th>'+$(this).children('name').text()+'</th>')
.append('<th>学生</th>')
.append('<th>'+$(this).attr('age')+'</th>')
.append('<th>'+$(this).children('email').text()+'</th>')
.append('<th>'+$(this).children('phone').text()+'</th>')
.appendTo($('table'));
});
$(xml).find('teacher').each(function(){
$('<tr></tr>').append('<th></th>')
.append('<th>'+$(this).children('name').text()+'</th>')
.append('<th>老师</th>')
.append('<th>'+$(this).attr('age')+'</th>')
.append('<th>'+$(this).children('email').text()+'</th>')
.append('<th>'+$(this).children('phone').text()+'</th>')
.appendTo($('table'));
});
},
error: function(){
alert('无法获取xml文件');
}
});
});
效果如图
其实jQuery
中只需要$(xml)
就可以像操作html
一样操作xml