How To Parse XML Using jQuery and Ajax

How To Parse XML Using jQuery and Ajax
October 26, 200912 Comments

In this tutorial I will show you how to parse or process an xml document to display the data on a page in html form. It can be used to filter raw RSS feeds, set up a cool sitemap on your blog or even the groundwork for your own search auto complete.

Note: Running this locally on your machine will more than likely not work because of security features. Try it on a server instead.

Harnessing jQuery's Ajax API and making it do most of the work for us, leaves only the simple tasks of formatting how our data will displayed on the page while it is being parsed. This whole process is fairly easy to implement.

Getting Started

There are only two pre-requisites to this tutorial, an xml file and of course jQuery CDN linked in either your header or your footer.

In a new document, I've already laid out the page and created a un-ordered list to house our formatted data once it comes out the other end. The #loading div shows the loading animation on page load and once our function is ran, it displays it until the function is done.

In the Ajax call, we have four basic parameters. The type of call we are doing is a GET, basically telling the Ajax to get this file. The url is the path to the file we are getting the data from. The dataType states obviously which type of data is being grabbed, and finally success tells the Ajax what function or action to run once the xml is ready to be parsed.

Setting up the Ajax call

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $("#loading").show();
  $.ajax({
    type: "GET",
    url: "sitemap.xml",
    dataType: "xml",
    success: parseXml
});
</script>
</head>
<body>
<div id="wrap">
<ul id="site_list">
<li id="loading"><img src="images/ajax-loader.gif" alt="loading" /> Loading Data..</li>
</ul>
</div>
</body>
</html>

Setting Up the Parse Function

For the parsing of the xml file we're going to set up a function that will search each parent element and output the specified child element's value as text using the find and each statement. In the xml file the format consists of a parent element being "url" and the child elements contained within such as this:


  http://www.vagrantradio.com/
  2009-10-22T00:42:12+00:00
  daily
1.0

In the first line of our function we will simply search each element of "url", then in the following lines append each instance of "loc" (being the url in our sitemap), to the #site_list unordered list with "li" tags and wrap it in a link. Once the function has finished loading the xml to the page, the loading animation is hidden.

function parseXml(xml) {
$(xml).find("url").each(function() {
//find each instance of loc in xml file and wrap it in a link
$("ul#site_list").append('<li>' + '<a href="' + $(this).find("loc").text() + '">' + $(this).find("loc").text() + '</a>' + '</li>');
$("#loading").hide();
 });
}
});

The Complete Code

Now we have an easy way to grab RSS feeds or XML documents and display them without a plug-in or sidebar widget. Below is the complete code with functions to parse and format XML documents. Don't forget to check out the demo to see how it works and download the provided source files zipped up so you can tear it apart and make something useful with it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $("#loading").show();
  $.ajax({
    type: "GET",
    url: "sitemap.xml",
    dataType: "xml",
    success: parseXml
});
function parseXml(xml) {
$(xml).find("url").each(function() {
//find each instance of loc in xml file and wrap it in a link
$("ul#site_list").append('<li>' + '<a href="' + $(this).find("loc").text() + '">' + $(this).find("loc").text() + '</a>' + '</li>');
$("#loading").hide();
 });
}
});
</script>
</head>
<body>
<div id="wrap">
<ul id="site_list">
<li id="loading"><img src="images/ajax-loader.gif" alt="loading" /> Loading Data..</li>
</ul>
</div>
</body>
</html>

Thanks for reading!

Author: Jason

Hi, I'm Jason. A front end developer from Grand Rapids, Michigan, and founder of VagrantRadio. I enjoy working with Css, jQuery, Php, learning new techniques in Photoshop and you should follow me on Twitter or Snipplr.

Mojo Themes
  • http://www.samialsayyed.com Sami

    Can you please help me with this:
    I dont have the xml file stored locally, I want to call a servlet that will generate the xml file. I am trying to put the full servlet url but it is not working!

    Thank you so much

    • http://www.vagrantradio.com Jason Pant

      Sami,

      I’m afraid this technique only works for static xml for now, I’ve tried it on dynamically created xml and the lack of an actual url to call it from doesn’t do much of anything. Sorry I couldn’t help!

  • Anthony

    I am having trouble getting the source code to run properly. I can view the demo fine, but when I load the source code to test it all I get is the Loading… message. Any idea what I may need to do to fix this? I have tried it on a couple different systems with the same result.

    Thanks!

    • http://www.vagrantradio.com Jason Pant

      Anthony,

      Are you trying to run the source code un-edited from the zip file or have you edited it to parse your own file?

  • Caushik

    The above code does not work in IE 7 but works in google chrome. Should I change IE settings to make the above code work.

    • http://www.vagrantradio.com Jason Pant

      I don’t know what you mean by change settings so it works in IE7, but it works fine for me in IE7 and the other browsers I tested it in.

  • wolf3d

    Hei im new with jQuery… i just dont get it how to modify Your code to make parser get a specific par of xml file, not the all of it.
    THX. Your answer will be appreciated ;)

  • Genzer

    I’ve tested this demo in IE8 and it didn’t work. But it works fine in Opera and Chrome. Any suggestions?

    • http://www.vagrantradio.com Jason Pant

      Genzer,

      As I stated above it does work in IE. I just tested it in IE7, IE8 and all other major browsers and it works just fine.

  • baltixz

    thanks for this code it’s really very helpful. It works perfectly on IE7, IE8, Firefox, Opera both win & mac. It’s better to load the samples in your own dev server and not on your local machines.

  • http://www.vagrantradio.com VagrantRadio

    Note that many of the problems mentioned above are because of testing locally. Run on an actual web server for correct results.

  • http://www.vagrantradio.com VagrantRadio

    For those having problems running this script locally, it should be noted that jQuery doesn’t allow ajax loading of external scripts. The file being called has to be on the same server as the script calling it.

    For instance, if I try and load an xml file from Google it isn’t going to work.

    Those testing this on a local server, give this a try: http://stackoverflow.com/questions/5282058/how-to-parse-xml-with-jquery-on-a-local-computer

Scroll to top