XML Parsing with jQuery 【转】

简介:

XML Parsing with jQuery

Posted in:

XML is an important part of AJAX. Heck, it's right in the name, "Asynchronous JavaScript and XML", so knowing how to parse XML is equally important. This tutorial will demonstrate how to parse XML using jQuery that should cover almost all cases you'd typically run into.

Using jQuery to parse XML is vaguely reminiscent of LINQ in the recent .NET frameworks. That's a good thing, since LINQ made parsing XML in .NET vastly easier than previous techniques. With jQuery, when you receive XML from a callback, you're not actually getting raw text, you're actually getting a DOM (document object model) that jQuery can traverse very quickly and efficiently to give you the data you need.

Let's start by looking at the example XML document we'll be parsing today. I made a file that contains most things you'd see in a typical XML document - attributes, nested tags, and collections.

<?xml  version= "1.0"  encoding= "utf-8"  ?>
<RecentTutorials>
   <Tutorial  author= "The Reddest" >
     <Title>Silverlight and the Netflix API </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>Silverlight 2.0 </Category>
       <Category>Silverlight </Category>
       <Category>C# </Category>
       <Category>XAML </Category>
     </Categories>
     <Date>1/13/2009 </Date>
   </Tutorial>
   <Tutorial  author= "The Hairiest" >
     <Title>Cake PHP 4 - Saving and Validating Data </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>CakePHP </Category>
       <Category>PHP </Category>
     </Categories>
     <Date>1/12/2009 </Date>
   </Tutorial>
   <Tutorial  author= "The Tallest" >
     <Title>Silverlight 2 - Using initParams </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>Silverlight 2.0 </Category>
       <Category>Silverlight </Category>
       <Category>C# </Category>
       <Category>HTML </Category>
     </Categories>
     <Date>1/6/2009 </Date>
</Tutorial>
   <Tutorial  author= "The Fattest" >
     <Title>Controlling iTunes with AutoHotkey </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>AutoHotkey </Category>
     </Categories>
     <Date>12/12/2008 </Date>
   </Tutorial>
</RecentTutorials>

 

The first thing you're going to have to do is write some jQuery to request the XML document. This is a very simple AJAX request for the file.

$(document).ready( function()
{
  $.ajax({
    type:  "GET",
    url:  "jquery_xml.xml",
    dataType:  "xml",
    success: parseXml
  });
});

 

Now that that's out of the way, we can start parsing the XML. As you can see, when the request succeeds, the function parseXML is called. That's where I'm going to put my code. Let's start by finding the author of each tutorial, which are stored as attributes on the Tutorial tag.

function parseXml(xml)
{
   //find every Tutorial and print the author
  $(xml).find( "Tutorial").each( function()
  {
    $( "#output").append($( this).attr( "author") +  "<br />");
  });

   // Output:
   // The Reddest
   // The Hairiest
   // The Tallest
   // The Fattest
}

 

The quickest way to parse an XML document is to make use of jQuery's powerful selector system, so the first thing I do is call find to get a collection of every Tutorial element. Then I call each, which executes the supplied function on every element. Inside the function body, this now points to a Tutorial element. To get an attribute's value, I simply call attr and pass it the name of what attribute I want. In this example, I have a simple HTML span object with an id of "output". I call append on this element to populate it with data. You would probably do something a little more exciting, but I just wanted a simple way to display the results.

See how easy that is? Let's now look at a slightly more complicated one. Here I want to print the publish date of each tutorial followed by the title.

//print the date followed by the title of each tutorial
$(xml).find( "Tutorial").each( function()
{
  $( "#output").append($( this).find( "Date").text());
  $( "#output").append( ": " + $( this).find( "Title").text() +  "<br />");
});

// Output:
// 1/13/2009: Silverlight and the Netflix API
// 1/12/2009: Cake PHP 4 - Saving and Validating Data
// 1/6/2009: Silverlight 2 - Using initParams
// 12/12/2008: Controlling iTunes with AutoHotkey

 

This is very similar to the previous example, except now the values are stored inside element text instead of attributes. Again, I want to go through every Tutorial tag, so I first use find and each. Once I'm inside a Tutorial, I need to find the Date, so I use find again. To get the text inside an XML element, simply call text. I repeat the same process again for the Title, and that's it.

We've now parsed every piece of information except the categories that each tutorial belongs to. Here's the code to do that.

//print each tutorial title followed by their categories
$(xml).find( "Tutorial").each( function()
{
  $( "#output").append($( this).find( "Title").text() +  "<br />");

  $( this).find( "Category").each( function()
  {
    $( "#output").append($( this).text() +  "<br />");
  });

  $( "#output").append( "<br />");
});

// Output:
// Silverlight and the Netflix API
// Tutorials
// Silverlight 2.0
// Silverlight
// C#
// XAML

// Cake PHP 4 - Saving and Validating Data
// Tutorials
// CakePHP
// PHP

// Silverlight 2 - Using initParams
// Tutorials
// Silverlight 2.0
// Silverlight
// C#
// HTML

// Controlling iTunes with AutoHotkey
// Tutorials
// AutoHotkey

 

Once again, I get every Tutorial by using find and each. I then get the Title in the same was as the previous example. Since a tutorial can belong to several categories, I call find and each to iterate over each Category element inside a tutorial. Once I'm inside a Category element, I simple print out its contents using the text function.

Being able to parse elements, attributes, and collections should cover almost every form of XML you'd ever see, and making use of jQuery selectors to get the job done makes parsing XML in JavaScript a breeze. That does it for this tutorial. Hopefully we all learned something about jQuery and XML.

 

from:http://www.switchonthecode.com/tutorials/xml-parsing-with-jquery

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!

















本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2009/12/29/1635204.html ,如需转载请自行联系原作者



相关文章
|
XML Android开发 数据格式
IOException parsing XML document from class path resource [applicationContext.xml];
IOException parsing XML document from class path resource [applicationContext.xml];
|
XML 存储 JSON
【jquery】前端数据格式:json、xml对比
【jquery】前端数据格式:json、xml对比
131 0
|
XML JavaScript 数据格式
JQuery 动态XML字符串添加节点
今天实现了动态的给一个XML字符串添加节点。
148 0
|
Java 数据库连接 Maven
org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgume
org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgume
544 0
|
XML JavaScript 数据格式
jQuery|前后台xml交互就靠它了
$.parseXML()函数用于将字符串解析为对应的XML文档。 提示:该函数将使用浏览器内置的解析函数来创建一个有效的XML文档,该文档可以传入jQuery()函数来创建一个典型的jQuery对象,从而对其进行遍历或其他操作。
1175 0
|
1月前
|
XML 前端开发 Java
讲解SSM的xml文件
本文详细介绍了SSM框架中的xml配置文件,包括springMVC.xml和applicationContext.xml,涉及组件扫描、数据源配置、事务管理、MyBatis集成以及Spring MVC的视图解析器配置。
57 1
|
3月前
|
XML Java 数据格式
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
这篇文章是Spring5框架的实战教程,主要介绍了如何在Spring的IOC容器中通过XML配置方式使用外部属性文件来管理Bean,特别是数据库连接池的配置。文章详细讲解了创建属性文件、引入属性文件到Spring配置、以及如何使用属性占位符来引用属性文件中的值。
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)