Load Data From An XML File With jQuery

Evening Tip: Use jQuery To Retrieve Data From An XML File

In this quick tip, I’ll show you how to load data from an XML file onto a blank page. We’ll work with the $.get function and will also implement a loading gif while the information is being retrieved. We’ll be displaying a simple list of recommended web development books. Let’s go ahead and get started.

Step One: Review The Script

First, let’s take a look at our simple XML file. It merely contains a few books along with their title, image and description.

<?xml version="1.0" encoding="utf-8" ?>
<books>
    <book title="CSS Mastery" imageurl="images/css.jpg">
    <description>
    info goes here.
    </description>
    </book>

    <book title="Professional ASP.NET" imageurl="images/asp.jpg">
    <description>
    info goes here.
    </description>
    </book>

    <book title="Learning jQuery" imageurl="images/lj.jpg">
    <description>
    info goes here.
    </description>
    </book>
</books>

Next, let’s take a look at the actual jQuery.

    $(document).ready(function()
      {
        $.get('myData.xml', function(d){
        $('body').append('<h1> Recommended Web Development Books </h1>');
        $('body').append('
'); $(d).find('book').each(function(){ var $book = $(this); var title = $book.attr("title"); var description = $book.find('description').text(); var imageurl = $book.attr('imageurl'); var html = '<dt> <img class="bookImage" alt="" src="' + imageurl + '" /> </dt>'; html += '<dd> <span class="loadingPic" alt="Loading" />'; html += '<p class="title">' + title + '</p>'; html += '<p> ' + description + '</p>' ; html += '</dd>'; $('dl').append($(html)); $('.loadingPic').fadeOut(1400); }); }); });

Step Two: Decipher Time

Because this is a quick tip, I’ll run through the script a bit quicker than I usually would. When the document is ready to be manipulated, we’re going to fetch our XML file using the “$.get” function. In the parenthesis, we’ll pass in the location of the file, and then we’ll run a callback function. I’ll use the variable “d” to represent the information that was pulled from the XML file. Next, we’re going to create a heading tag and a definition list.

Continuing on, we’re going to search through the XML file (d) and find the tag entitled “book”. Referring back to my document, there are three books. Consequently, we’ll need to run the “each” method in order to perform an operation for each book. Remember, “each” is just like the “for” statements. It’s a way to run through each element in the wrapped set.

In the next block of code, I’m defining a few variables. In order to get the “title” and “description” from our XML file, we use “.attr(value)” – where “value” is equal to the attribute within the tag.

Lastly, we’re creating a variable called “html” that will contain the html that will display the information from our XML file. Merely assigning that information to the variable won’t display it on the page, however. To add it to the page, we grab the definition list and append the variable. – $(‘dl’).append($(html));

One more thing worth mentioning is that, while the information is being retrieved from the XML file, we’ll display a standard loading gif (via a background image). When the data has loaded, we’ll grab the image and fade it out.

You’re Done

I know I went through that somewhat quickly; So feel free to leave a comment and ask any questions that you might have. It should be noted that this script will require a bit more work before it becomes ready for a real world website. You have to compensate for people that have Javascript turned off. In this case, if they did have it off, they would be staring at a blank page. You must compensate for such things. But, I digress.

Add Comment

Discussion 84 Comments

Comment Page 1 of 21 2
  1. Good idea i like it. I might use this for a project

  2. Chris says:

    JQuery is so powerful & dynamic.

    I think I’m in love.

    Keep these JQuery tuts coming!

  3. anonymous coward says:

    seems like these tutorials are getting lame. if you don’t have to write a full article, don’t publish it. And certainly don’t spend time in your already über short drivel telling me how quick and short this will be.

  4. Brian says:

    This might be a basic question (I’m still getting my feet wet with Javascript), but why is the $book variable preceded by a dollar sign? I suspect it has something to do with the jQuery function.

  5. Interesting how jQuery does it. I actually find jQuery a little too cryptic for my tastes. It feels too easy to jam so much into a single line; code becomes harder to read. Mootools and Prototype both have pretty ways of accessing AJAX. :)

    Ps. You got a run-away em tag making the rest of the page in italics.

  6. George Burrell says:

    Just what I was after! Thanks guys! I like the format of having some smaller ‘evening tips’ style tuts! Keep up the good work!

  7. Great tip :D jQuery is brilliant for little things like this

  8. Dan Harper says:

    Thanks for the tip!

  9. Dan Harper says:

    BTW, I think maybe you didn’t close an em tag or something? Everything’s in italics!

  10. Ronny-André says:

    Wow thanks! This is actually very very valuable code!

  11. Vin Thomas says:

    Holy Moly! I love this stuff! I am just learning jquery and I can’t get enough of it. It is winning the javascript war in my books!

    Thanks a ton for all your great tips! I REALLY appreciate it!

  12. Braden Keith says:

    this would of been helpful this morning when I was dealing with this. For now on I check nettuts before going into work.

  13. Braden Keith says:

    When did the comments go italicized?

  14. Zach Dunn says:

    I get terribly excited when I see jQuery on my RSS feed. When it turns out to be useful? That’s double the excitement. Great tutorial!

  15. Dan says:

    What’s the point of using XML? Couldn’t you just as easily hard code that or stick it in a database?

    *Confused*

    Also, where are those weekly PHP tutorials?

  16. Jeffrey Way says:
    Author

    @Dan – Ahh, sorry about that. It’s been fixed. :)

    @The Other Dan – In this situation – yeah, you could just hard-code it. But what about if you were pulling from an RSS file…or something similar? The example is intentionally simple – but the uses are widespread.

  17. Jeffrey Way says:
    Author

    @Brian – It isn’t required…but is usually considered to be a good practice. It reminds us that we’re dealing with jQuery.

  18. Connor says:

    Man this is very useful. Right now I’m working on a flash calendar that runs off an xml page. Now, I could be super accessible and create a non flash version that runs off the same sheet using JQuery.

  19. mattems says:

    awesome..simple and to the point, definately not for the novice javascripter as the explanation is low. But i loved it.

    “This might be a basic question (I’m still getting my feet wet with Javascript), but why is the $book variable preceded by a dollar sign? I suspect it has something to do with the jQuery function.”

    definately a typo, obviously a php developer :)

    rock on

  20. Tom says:

    Great, now a tut that will help to parse xml as html.

  21. Shane says:

    Interesting stuff. I’ve never done this with jQuery and XML – I’m sure it’ll come in use some time in the near future.

    Just one thing – that second book – ASP.NET – what’s that? ;)

    Any plans for ASP.NET tutorials on the site?

  22. BroOf says:

    I love you for this great post ;D

  23. Cool gonna try iy out soon!

  24. Jeffrey Way says:
    Author

    @Shane – I’d love to have ASP.NET tutorials. It’s my framework of choice. But, I’m not sure that there is enough of a demand for it. If enough people asked for them, I would absolutely get some up.

  25. Damien says:

    Some simple asp.net tutorials would be ace, I like this how would extending this work though so that it could fall over ok without js??

    Cheers

    Damien

  26. Several things…

    First: you don’t need the full $(document)…bit, just pass the function to an empty jQuery call:
    $(function() {
    // … do stuff when the DOM is ready …
    }

    Second: the loading icon should be attached to the body BEFORE you do anything. Then load the XML, parse it, drop the content into your DL and remove the loading animation. Adding the loading animation at the same time you’re adding the content to which it is a metaphor for loading makes the loading icon unneccessary as you’re seeing it AFTER the content has been loaded and added to the page.

    Third: accessing an attribute, storing it in a variable and then retrieving the value is far more expensive than just accessing the attribute. Several of the variable definitions are unnecessary.

    Fourth: instead of wasting time building a string, passing it to jQuery, having jQuery expand it and append each item, just append the items as necessary.

    Here’s a cleaned-up version:

    $(function() {
    $.get(‘myData.xml’, function(d){
    $(‘body’).append(‘Recommended Web Development Books’);

    $(d).find(‘book’).each(function(){
    var book = $(this);

    $(‘dl’)
    .append(” + book.attr(‘title’) + ”)
    .find(‘dd’)
    .append(”)
    .append(” + book.attr(‘title’) + ”)
    .append(” + book.find(‘description’).text() + ”);
    });
    });
    });

  27. Sorry, forgot to escape my gt/lt:

    $(function() {
    $.get(‘myData.xml’, function(d){
    $(‘body’).append(‘<h1>Recommended Web Development Books</h1><dl></dl>’);

    $(d).find(‘book’).each(function(){
    var book = $(this);

    $(‘dl’)
    .append(‘<dt>’ + book.attr(‘title’) + ‘</dt><dd></dd>’)
    .find(‘dd’)
    .append(‘<img class=”bookImage” alt=”" src=”‘ + book.attr(‘imageurl’) + ‘” />’)
    .append(‘<p class=”title”>’ + book.attr(‘title’) + ‘</p>’)
    .append(‘<p>’ + book.find(‘description’).text() + ‘</p>’);
    });
    });
    });

  28. Khaled says:

    Hello,

    nice tut, but it’s not working in IE and it’s a shame for jQuery that XML parsing is not working well for IE. I’ve talked to some jQuery folks @IRC and they told me the same thing … it’s kind of shortage … and for that there exists a class named: XML2JSON (www.fyneworks.com/jquery/xml-to-json/)

  29. Jeffrey Way says:
    Author

    @Khaled – I just checked the demo in IE7 and IE6. It works just fine. Am I missing something? Anybody else notice anything?

  30. Khaled says:

    Don’t try the demo on nettuts … try it on your pc … download the demo and try it on your pc without a server

  31. Ben says:

    What about CData? I’m using an xml file for my flash content and cdata in order to have some formatting – I’d then like to use the xml content as alternative content for the flash. But it seems that any js xml retriever fails when it hits the Cdata. Any Tips?

  32. Mike Bobiney says:

    Demo works fine for me.

    If this were put to actual use I might have added a css class to the dl element to prevent from accidentally selecting multiple occurrences.

  33. Zarathustra says:

    Could someone talk me/us through the process of parsing a Flickr xml feed using this principle? I am trying without much success. With this extra example in the thread I am sure many people would benefit. Thanks a lot.

  34. Zarathustra says:

    This script has “done the job” for me (on a non-wordpress site btw). But as (as usual!) I wish I understood it better. Still, a walkthrough of using jQuery to manipulate a Flick feed would be a great tutorial. And definitely more “real world” useful than your example above, although I understand it was a quick tip :)

    Link: http://www.nulldevice.de/2008/05/flickr-rss-feed-plugin-for-jquery-and-wordpress/

  35. Milinda says:

    According to my experience jQuery can’t handle XML with namespaces(namespaces handling is a must when it comes to web services related interactions). Currently Firefox and IE handle XML with namespaces in two different ways and jQuery can’t handle that. I have blogged about this problem here(http://mpathirage.com/why-most-popular-javascript-libraries-doesnt-support-xml-with-namespaces/). And the solution is available here(http://mpathirage.com/solution-to-xml-namespace-problem-in-getelementsbytagname/).

  36. When i clicked on this i didn’t think it would be helpful but it actaually was thanks NETTUTS

  37. James says:

    Using this right now – making a template for TF!! … Thanks Jeffrey! :)

  38. Mike says:

    Here’s Michael T’s code from above reformatted slightly so it works with the rest of the demo:

    $(function()
    {
    $.get(‘myData.xml’, function(d)
    {
    $(‘body’).append(‘Recommended Web Development Books’);

    $(d).find(‘book’).each(function()
    {
    var book = $(this);

    $(‘dl’)
    .append(” + ” + ”)
    .append(‘ ‘ + book.attr(‘title’) + ‘ ‘ + book.find(‘description’).text() + ‘ ‘);
    });
    });
    });

  39. Mike says:

    Or … not. Looks like the form validation script ate it.

  40. alterIdealism says:

    What about saving data into a XML file?
    Or isn’t that possible with just client-based scripts?

  41. fornetti says:

    I do not believe this

  42. Miguel says:

    Awesome tutorial! But what would it take to add a set of navigational buttons via the xml file?

  43. Aamir Afridi says:

    This is a very nice tip. But do anyone know how to access XML namespaces?

  44. Ng Xuan Mui says:

    nice. But if data return is xml (not in a file), how do U process ? I test in IE6, if I read a xml file, no prob, but when I test on data return, it’s xml, too, but nothing appear :(

    Thanks for ur solution

  45. kareem says:

    this is wonderful tutorial i will put acopy of this lesson on
    my site here
    http://www.as7ap4you.com

  46. Jimmy says:

    @mattems and Brian

    I don’t think adding a dollar sign in front of the variable is a typo. I thought it was too when I first saw this practice, and it does seem php related, but I’ve seen it being used in jQuery scripts pretty frequently. It’s just is an easy way of distinguishing between variables.

    Most variables will be a string or a number maybe, but by adding the dollar sign, you can be clear that it’s a jQuery object being stored there (if you stick to the practice). You can still access all your usual jQuery functions, but from an easier to read (and more visually appropriate with the $) variable.

    e.g.
    var $navitem = $(“#nav li:first”);
    $listitem.fadeOut(“slow”);

  47. Great tutorial, I had a hard time doing something similar on my page to make a easy updatable catalog of cd’s, so that anyone could add their cd to the list. You’ve just made my life easier.

  48. anemia says:

    online demo works but not offline ie7

  49. Ben says:

    Hi there,

    Thanks for the tutorial, but I was wondering is it possible to load XML generated by a servlet? So there is no myData.xml just a URL?

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.