Magic Studio

专心做有逼格的APP!

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

posted on 2009-12-29 16:27  Mr 布鲁斯  阅读(434)  评论(0编辑  收藏  举报

导航