irwan

XML Parsing with jQuery

Apr 22nd, 2012
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
XML 6.04 KB | None | 0 0
  1. 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.
  2.  
  3. 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.
  4.  
  5. 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.
  6.  
  7. <?xml version="1.0" encoding="utf-8" ?>
  8. <RecentTutorials>
  9.   <Tutorial author="The Reddest">
  10.     <Title>Silverlight and the Netflix API</Title>
  11.     <Categories>
  12.       <Category>Tutorials</Category>
  13.       <Category>Silverlight 2.0</Category>
  14.       <Category>Silverlight</Category>
  15.       <Category>C#</Category>
  16.       <Category>XAML</Category>
  17.     </Categories>
  18.     <Date>1/13/2009</Date>
  19.   </Tutorial>
  20.   <Tutorial author="The Hairiest">
  21.     <Title>Cake PHP 4 - Saving and Validating Data</Title>
  22.     <Categories>
  23.       <Category>Tutorials</Category>
  24.       <Category>CakePHP</Category>
  25.       <Category>PHP</Category>
  26.     </Categories>
  27.     <Date>1/12/2009</Date>
  28.   </Tutorial>
  29.   <Tutorial author="The Tallest">
  30.     <Title>Silverlight 2 - Using initParams</Title>
  31.     <Categories>
  32.       <Category>Tutorials</Category>
  33.       <Category>Silverlight 2.0</Category>
  34.       <Category>Silverlight</Category>
  35.       <Category>C#</Category>
  36.       <Category>HTML</Category>
  37.     </Categories>
  38.     <Date>1/6/2009</Date>
  39. </Tutorial>
  40.   <Tutorial author="The Fattest">
  41.     <Title>Controlling iTunes with AutoHotkey</Title>
  42.     <Categories>
  43.       <Category>Tutorials</Category>
  44.       <Category>AutoHotkey</Category>
  45.     </Categories>
  46.     <Date>12/12/2008</Date>
  47.   </Tutorial>
  48. </RecentTutorials>
  49.  
  50. 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.
  51.  
  52. $(document).ready(function()
  53. {
  54.   $.ajax({
  55.     type: "GET",
  56.     url: "jquery_xml.xml",
  57.     dataType: "xml",
  58.     success: parseXml
  59.   });
  60. });
  61.  
  62. 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.
  63.  
  64. function parseXml(xml)
  65. {
  66.   //find every Tutorial and print the author
  67.   $(xml).find("Tutorial").each(function()
  68.   {
  69.     $("#output").append($(this).attr("author") + "<br />");
  70.   });
  71.  
  72.   // Output:
  73.   // The Reddest
  74.   // The Hairiest
  75.   // The Tallest
  76.   // The Fattest
  77. }
  78.  
  79. 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.
  80.  
  81. 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.
  82.  
  83. //print the date followed by the title of each tutorial
  84. $(xml).find("Tutorial").each(function()
  85. {
  86.   $("#output").append($(this).find("Date").text());
  87.   $("#output").append(": " + $(this).find("Title").text() + "<br />");
  88. });
  89.  
  90. // Output:
  91. // 1/13/2009: Silverlight and the Netflix API
  92. // 1/12/2009: Cake PHP 4 - Saving and Validating Data
  93. // 1/6/2009: Silverlight 2 - Using initParams
  94. // 12/12/2008: Controlling iTunes with AutoHotkey
  95.  
  96. 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.
  97.  
  98. We've now parsed every piece of information except the categories that each tutorial belongs to. Here's the code to do that.
  99.  
  100. //print each tutorial title followed by their categories
  101. $(xml).find("Tutorial").each(function()
  102. {
  103.   $("#output").append($(this).find("Title").text() + "<br />");
  104.  
  105.   $(this).find("Category").each(function()
  106.   {
  107.     $("#output").append($(this).text() + "<br />");
  108.   });
  109.  
  110.   $("#output").append("<br />");
  111. });
  112.  
  113. // Output:
  114. // Silverlight and the Netflix API
  115. // Tutorials
  116. // Silverlight 2.0
  117. // Silverlight
  118. // C#
  119. // XAML
  120.  
  121. // Cake PHP 4 - Saving and Validating Data
  122. // Tutorials
  123. // CakePHP
  124. // PHP
  125.  
  126. // Silverlight 2 - Using initParams
  127. // Tutorials
  128. // Silverlight 2.0
  129. // Silverlight
  130. // C#
  131. // HTML
  132.  
  133. // Controlling iTunes with AutoHotkey
  134. // Tutorials
  135. // AutoHotkey
  136.  
  137. 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.
  138.  
  139. 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.
Advertisement
Add Comment
Please, Sign In to add comment