Load Data From An XML File With jQuery

Quick Tip: Use jQuery to Retrieve Data From an XML File

Tutorial Details
  • Difficulty: Beginner
  • Completion Time: 15 Minutes

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.

Tags: jQuery
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.benmacgowan.co.uk Ben

    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?

  • Dan

    What if the xml doc has 100 items and you only want the top 10?

  • Vahid
  • Gary Ricke

    Thanks!

    I tried 3 different jQuery samples and all failed in IE until this one.

    Cheers!

  • Logan

    Like Ben, I would like to use this with a remote address. Is this possible? It doesn’t seen to work when I replace the local file with a URL.

  • celco

    Hi thanks nettuts nice tutorial – question how do you add links in ht XML file to show up? is this the namespace issue or something else.

    All I want ot do is make the books as links…

    any help would be appreciated.

  • JP

    Yes online demo works fine in IE7 but not offline. Why?

  • Sagar S. Ranpise

    Awesome bro. Thanks a lot for sharing. Keep doing the good work..

    With Regards,
    Sagar S. Ranpise :-)

  • ravi

    please let me know how to fetch the particular data from the xm. for example 2nd element from book note. please help its urgent

  • bay

    This is Great!
    here’s a quick question..
    I’m very VERY new to all this…
    say if I have three buttons…each with ID 1, 2, and 3.
    I have an xml file with 3 different pieces of info each with an id of 1, 2, and 3 as well. How would I make a string that takes the id of the button…matches it to the ID of the xml…then spits out the corresponding info?

  • Pingback: All my bookmarks ever | Daniel John Gayle

  • Allen Mackley

    Jeffery, thank you for this great tip, it helped me out tremendously. I’ve got it working within my project, but there’s still a couple concepts I don’t quite understand.

    For example, why is the “d” necessary? What’s it stand for, what value is it and what’s exactly going on there?

    In your tip you say:
    “I’ll use the variable “d” to represent the information that was pulled from the XML file.”

    Could “d” be any other letter or word as well? Why do we need “d” to represent the file?

    The other question I have concerns this: “.append($(html));”
    I know what’s going on there for the most part, except I don’t understand why you need two pairs of parenthesis. Why is the extra pair necessary? (For example, would it work to just write “.append(html);” ?

  • Pingback: Tutoriales de la web para tu web » Blog Archive » Uso jQuery para recuperar datos de un archivo XML

  • Nano

    Making Michael T’s and Mike’s script just a little bit better:

    replace:
    $(d).find(’book’).each(function()

    with:
    $(‘book’, d).each(function()

  • bebeboo

    great post!

    i want to ask about this case, btw, if it’s not much trouble:

    say i have:

    lorem ipsum dolor hello world! lorem ipsum dolor et

    thisimage

    lorem ipsum dolor lorem ipsum dolor et

    i need to process each tag sequentially and output it in a similar way that a browser may output basic html tags (like anchors, spans, etc inside p tags)

    can i do that by just using for/each? or should i restructure my xml ?

    thank you in advance!

  • bebeboo

    oops, tags not allowed, here it is:

    lorem ipsum dolor hello world! lorem ipsum dolor et

    thisimage

    lorem ipsum dolor lorem ipsum dolor et

  • Pingback: Top 20 Ajax Tutorials | Web Design Tutorials | Creating a Website | Learn Adobe Flash, Photoshop and Dreamweaver

  • David

    Has anyone figured out how to load in an external file using a full URL (e.g. http://example.com/example.xml)?

  • Andy

    I need to load two xml files on a single page. The second one is loaded depending on the data in the first one. I’m using the code above and the code seems to be conflicting . . . I can load only one XML file If I don’t load the first one the second one loads fine.

    Please help

  • Kency

    it good tip but not work on IE
    my OS is windows 7 anh i use Expression web compile code
    anh when i run this code
    it work fine on Firefox but IE notwork

  • Kency
  • http://twitter.com/mike_ebert/ Mike Ebert

    @David – you can’t use a URL that isn’t on your domain with AJAX–being able to do so would represent a potential security problem. You can get around this with a “proxy” server-side script–a server side script that fetches content from an external URL and makes it available to the JS on your domain.

    jFeed uses a proxy.php file and has several examples: http://plugins.jquery.com/project/jFeed

  • Pingback: The Blog of Hanas › Dave Hanas finds random links around the web

  • Pingback: MyStreamTv.Com» MyStreamTv.Com

  • http://kucaburra.com/portfolio Websmythe

    I’m using the above in 2 js files, on the same page, with different “place-holders” (id=x-place-holder & id=y-place-holder), slightly different xml files and display routines. I’ve changed all vars except “html”. When the 2nd file runs it creates a duplicate in the other-place-holder, not called in the function. Does ajax have some kinda global scope or something??? (http://gracehappens.net)

  • kausar

    good demo…help me a lot…..thnkx for sharing

  • Pingback: Retrieve Data From an XML File Using jQuery « Ashish Design World

  • ryan

    First the admission, i’m a noob with jQuery,

    what i’m doing: i have a project i made in flash that uses data from an xml file to create a simple slide show to showcase items and it’s pretty simple, Image, 3-5 lines of text, and a URL. (for this instance URL is irrelevant as this client doesn’t want unique URLs) Instead of unique URLs, each image clicks through to a simple webpage i’m creating. In order to save myself time i’m trying to implement a solution like the one above. I’ve gone through many and this seems to be the most efficient. My goal is to use the exact same XML file for the flash execution and the web execution so i don’t have to hand code this in html… Only one problem.

    line 1
    line 2
    line 3
    line 4
    images/css.jpg

    this is the XML, with just one slide for testing purposes. All the text shows up fine, but i cannot seem to figure out how to get the picture to show up when I alter the xml from an attribute to a child element of the parent slide.

    $(document).ready(function()
    {
    $.get(‘myData.xml’, function(d){
    $(‘body’).append(”);

    $(d).find(‘book’).each(function(){

    var $book = $(this);
    var line1 = $book.find(‘line1′).text();
    var line2 = $book.find(‘line2′).text();
    var line3 = $book.find(‘line3′).text();
    var line4 = $book.find(‘line4′).text();

    var pic = $book.find(‘pic’).text;

    var html = ‘ ‘;
    html += ‘ ‘ + line1 + ” + line2 + ” + line3 + ” + line4 + ” ;
    html += ”;

    $(‘dl’).append($(html));

    });
    });
    });

    thanks!

    • Ryan

      here’s XML formated correctly for the blog display:

      < slide>
      < line1> line 1 </line1>
      < line2> line 2 </line2>
      < line3> line 3 </line3>
      < line4> line 4 </line4>
      < pic>images/css.jpg</pic>
      < /slide>

      < /slides>

    • ryan

      And the JS correctly formatted:

      < script type=”text/javascript”>

      $(document).ready(function()
      {
      $.get(‘myData.xml’, function(d){
      $(‘body’).append(‘< dl />’);

      $(d).find(‘book’).each(function(){

      var $book = $(this);
      var line1 = $book.find(‘line1′).text();
      var line2 = $book.find(‘line2′).text();
      var line3 = $book.find(‘line3′).text();
      var line4 = $book.find(‘line4′).text();

      var pic = $book.find(‘pic’).text;

      var html = ‘< dt> < img class=”bookImage” alt=”" src=”‘ + pic + ‘” /> < /dt>’;
      html += ‘< p> ‘ + line1 + ” + line2 + ” + line3 + ” + line4 + ‘< /p>’ ;
      html += ‘< /dd>’;

      $(‘dl’).append($(html));

      });
      });
      });
      < /script>

  • cuong

    I get the code in example, I can run demo online but I cannot run code offline. Who can tell me the reason why it goes.

    Thks

  • cuong

    It works well on Firefox offline. Why does not work on IE offline?

    Thx
    Cuong

  • http://www.graphicswebnetwork.com/default.aspx InDesign Tutorials

    Fantastic beat ! I wish to apprentice at the same time as you amend your site, how could i subscribe for a weblog site? The account aided me a acceptable deal. I were a little bit acquainted of this your broadcast provided vibrant clear concept

  • http://www.viewgraphic.net Jawad

    How can make image thumb link?

    In this link “What’s new in web” section i am using That script, now data is loading from XML file, i want thumb link, any one can help?
    http://viewgraphic.net/demo/sunshine/

    This is image url
    var imageurl = $project.attr(‘imageurl’);

    I want a hyper link to this image, how to call link for this code?

    Thanks

  • fguru

    Is anyone know why it’s not showing on Chrome. Firefox is fine.

    • Gideon

      I second that.

    • iliketurtlez

      You have to open Chrome with the “-allow-file-access-from-files” tag. Just create a new Chrome shortcut to look something like “C:UsersYourNameAppDataLocalGoogleChromeApplicationchrome.exe -allow-file-access-from-files -incognito”. I throw in -incognito as well since I don’t want caching while testing. Open this instance of Chrome first, then open your .html test file so that it opens into this instance rather than creating a normal Chrome instance without those flags. You can also just drag the .html file onto this instance of Chrome.

  • sv3n

    Hi Both I think the reason for this not working locally in Google Chrome may well be similar to one of the earlier comments regarding IE on a local machine or off line.

    If you mean it is not working when you view the actual site on the web in Google Chrome then not sure as it works when I view it.

    As I’m a newbie to though I could be wrong,

  • Isaac

    This is amazing, thanks.

  • jown

    It doenst work in IE and in Chrome, i dont have any clue why. Please can you update a working solution for local usage?

  • Tom

    Thanks! Im new to jquery and xml and this helped!

  • abhi

    Thanks for posting ..

  • Babulaas

    I have a xml file but i dont want to parse / show every node/block on my screen. I have a few links. If i click on one of these i want to load a specific node/block into a div or something. (it must be dynamic by using an attr in the link)

    Is this possible or must i parse evereything to an array?

  • divs

    HI,

    I am using jquery for first time. Very ncie tutorial . But i have few doubts and need help getting it clarified.
    a) Can we use just “append(html) instead of “append($(html))” in the line $(‘dl’).append($(html)); ?

  • http://www.facebook.com/people/Rick-Pascua/100001311758895 Rick Pascua

    much thanks for this, took me all but 5 mins to learn how to retrieve xml data thanks to you!

  • Kheang

    Great!

  • chikheang

    sorry, i just want to test the process comment!

  • chikheang

    i can read from XML file successfully! can anyone show me how to write to xml?

  • kheang

    hi!

  • http://www.facebook.com/rezwan.alin Rezwan Saki Alin

    Thanks. This is so helpful to me. But I want to add a new item for it. and that is the ‘Search Box’. Plz help me about it. just I type anything and data will be displayed from XML file. plz

  • Lim Chikheang

    hi

  • chikheang

    hi

  • PxlDancer

    how would you display a hyperlink for an xml feed