在jQuery中处理XML数据简单例子代码:
|
<员工> <姓名>麻花疼</姓名> <性别>男</性别> <年龄>40</年龄> <职位>疼逊CEO</职位> </员工> |
下面本文简单介绍如何使用 jQuery 载入一个 XML 文件并从中获取自己想要的数据。
准备 XML 文档及测试数据
假设我们现在要构建一个包含人员信息的 XML 文档,该 XML 文档要能反映其姓名、所在公司、公司简介、公司产品简介几个信息,那么我们可以把 XML 设计成如下样式:
|
<? xml
version = "1.0"
encoding = "utf-8"
?> < Persons > < Person
FullName = "Bill Gates" > < Corporation >Microsoft</ Corporation > < Description >The largest software company</ Description > < Products >Windows series OS, SQL Server Database, XBox 360...</ Products > </ Person > < Person
FullName = "Jobs" > < Corporation >Apple</ Corporation > < Description >The famous software company</ Description > < Products >Macintosh, iPhone, iPod, iPad...</ Products > </ Person > < Person
FullName = "Larry Page" > < Corporation >Google</ Corporation > < Description >the largest search engine</ Description > < Products >Google search, Google Adsense, Gmail...</ Products > </ Person > </ Persons > |
简单分析一下这个 XML 文件,其中第一行 <?xml version="1.0" encoding="utf-8" ?> 是声明此文档为 XML 文档,且文本编码为 utf-8。第二行及最后一行 Persons 为文档的根元素,然后每个 Person 元素即表示每个人,姓名存储在 Person 元素的 FullName 属性中,Corporation 元素用来存储所在公司名称,Description 元素用来存储公司简介,Products 元素用来存储公司产品简介。至此,该文档里面包含了比尔·盖茨、乔布斯、拉里·佩奇三位 IT 界大佬的信息。
用 jQuery 解析此 XML 文档
首先要用$.get()方法载入 XML 文件,然后用find()方法找到所有 Person 元素,再用 each() 方法进行遍历,代码如下:
|
<script type= "text/javascript" > jQuery(document).ready( function () { /* 先用 $.get 方法载入 XML 文件 */ $.get( "EmployeesInformation.xml" , function (xmlData) { /* 我们要讲得到的数据放入一个表格里面,这里定义一个表格字符窜 */ var
htmlData = "<table border='1'>" ; /* 找到 Person 元素,然后用 each 方法进行遍历 */ $(xmlData).find( "Person" ).each( function () { var
Person = $( this ); /* 将当前元素复制给 Person */ var
FullName = Person.attr( "FullName" ); /* 获取 Person 的 FullName 属性 */ var
Corporation = Person.find( "Corporation" ).text(); /* 获取 Person 中子元素 Corporation 的值 */ var
Description = Person.find( "Description" ).text(); /* 获取 Person 中子元素 Description 的值 */ var
Products = Person.find( "Products" ).text(); /* 获取 Person 中子元素 Products 的值 */ /* 将得到的数据,放到表格的一行中 */ htmlData += "<tr>" ; htmlData += " <td>"
+ FullName + "</td>" ; htmlData += " <td>"
+ Corporation + "</td>" ; htmlData += " <td>"
+ Description + "</td>" ; htmlData += " <td>"
+ Products + "</td>" ; htmlData += "</tr>" ; }); //完成表格字符窜 htmlData += "</table>" ; //将表格放到 body 中 $( "body" ).append(htmlData); }); }); </script> |
简单解释一下这段代码,由于此 XML 文档相对简单,所以这段代码也比较简短,代码中$.get()方法的第一个参数为 XML 文件地址,第二个参数是一个回调函数,回调函数中参数 xmlData 即为 XML 文件中的数据。在此示例中,我们打算 XML 中的数据以表格的形式显示在 HTML 中,所以先构建一个表格字符串 htmlData 先。
紧接着,用find()方法,找到所有名为 Person 的元素,因为每个 Person 元素即表示一个人,然后再用 each() 方法进行遍历,把遍历到的元素赋个一个变量 Person。用Person.attr()方法去除元素的 FullName 属性,也就是人员的姓名,再用find()方法找到其子元素 Corporation,Description 和 Products 并返回它们的文本内容,并用 tr 和 td 标签将它们包装在表格的一个行里面。最后完成表格字符串,并将表格添加到 body 标签中。