本文实例讲述了jQuery加载及解析XML文件的方法。分享给大家供大家参考,具体如下:
[b]1、简述[/b]
XML(eXtensible Markup Language)即可扩展标记语言,与HTML一样,都是属于SGML标准通用语言。
[b]2、 Content-Type[/b]
很多情况下XML文件不能正常解析都是由于Content-Type没有设置好。如果Content-Type本身就是一个XML文件则不需要设置;如果是由后台程序动态生成的,那么就需要设置Content-Type为“text/xml”,否则jQuery会以默认的“text/html”方式处理,导致解析失败。以下是几种常见语言中设置Content-Type的方式。
header("Content-Type:text/xml"); //PHP
response.ContentType = "text/xml"; //ASP
response.setContentType("text/xm"); //JSP
[b]3、创建实例XML文档(Student.xml)[/b]
<?xml version="1.0" encoding="utf-8" ?>
<stulist>
<student email="peter@163.com">
<name>peter</name>
<id>1</id>
</student>
<student email="ken@163.com">
<name>ken</name>
<id>2</id>
</student>
</stulist>
[b]4、获取XML[/b]
$(document).ready(function() {
$.ajax({
url: '/xml/Student.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000, //设定超时
cache: false, //禁用缓存
error: function(xml) {
alert("加载XML文档出错!");
},
success: GetStudentComplete //设置成功后回调函数
});
});
通过JQuery的Ajax函数进行读取。
[b]5、 解释XML[/b]
//获取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);
});
}
解析XML文档与解析DOM一样,也可以用find()、children()等函数来解析和用each()方法来进行遍历,另外也可以用text()和attr()方法来获取节点文本和属性。
[b]PS:这里再为大家提供几款关于xml操作相关在线工具供大家参考使用:[/b]
[b]在线XML/JSON互相转换工具:
[/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url]
[b]在线格式化XML/在线压缩XML:
[/b][url=http://tools.jb51.net/code/xmlformat]http://tools.jb51.net/code/xmlformat[/url]
[b]XML[/b][b]在线压缩/格式化工具:
[/b][url=http://tools.jb51.net/code/xml_format_compress]http://tools.jb51.net/code/xml_format_compress[/url]
[b]xml[/b][b]代码在线格式化美化工具:
[/b][url=http://tools.jb51.net/code/xmlcodeformat]http://tools.jb51.net/code/xmlcodeformat[/url]
更多关于jQuery相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/354.htm]jQuery操作xml技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/294.htm]jQuery操作json数据技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/451.htm]jQuery扩展技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/200.htm]jQuery常用插件及用法总结[/url]》、《[url=http://www.1sucai.cn/Special/430.htm]jQuery常见经典特效汇总[/url]》及《[url=http://www.1sucai.cn/Special/75.htm]jquery选择器用法总结[/url]》
希望本文所述对大家jQuery程序设计有所帮助。