Parse XML with jQuery

Parse XML with jQuery

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on March 16, 2010

I recently ran through the technique of parsing JSON with jQuery and thought i’d pick this up and show you how to parse XML. It’s pretty much the same although the big difference with using XML is that this won’t work for xml files that don’t sit outside of your domain as we’re making a standard AJAX request and you can’t make cross domain ajax request unless you’re using JSONP, more of which can be found here.

The XML

Here’s our XML code, and for the purpose of the demo i’ve saved it as books.xml. You can see that we have an XML node called ‘book’ these help to structure the xml file elements. You will see that each book has a title, description and date. You could for instance add an image tag or anything for that matter.

<?xml version="1.0" encoding="utf-8" ?>
<RecentBooks>
  <Book>
    <Title>My Cool Book Title</Title>
    <Description>The my cool book is possibly the best cool book in that any developer could use to be a great web designer.</Description>
    <Date>12/1/2010</Date>
  </Book>
  <Book>
    <Title>Another PHP book</Title>
    <Description>Learn everything about PHP with 'Another PHP book,' your ultimate guide to the ins and outs of PHP.</Description>
    <Date>4/1/2010</Date>
  </Book>
  <Book>
    <Title>jQuery Techniques</Title>
    <Description>jQuery techniques runs you through real life examples of jQuery from beginner to expert</Description>
    <Date>6/2/2010</Date>
  </Book>
  <Book>
    <Title>MySQL Database Book</Title>
    <Description>Brush up your knowledge with the best MySQL database book on the market.</Description>
    <Date>14/2/2010</Date>
  </Book>
</RecentBooks>

The JavaScript

The first thing we need to do in order to parse our XML file is to make an AJAX request to get the XML file, The XML file has to sit on the same domain as the JavaScript below because we can’t do cross domain AJAX requests.

IMPORTANT. Because of the nature of JavaScript you can’t make a cross domain AJAX request, this can only be achieved by using JSONP

Once we have the XML file we need to parse it and get the data that we need. The way we do this is by using the .find() function. By using this we can specify each book node and loop through them to get the data. We then append the data in to the .main div.

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "books.xml",
        dataType: "xml",
        success: xmlParser
    });
});

function xmlParser(xml) {

    $('#load').fadeOut();

    $(xml).find("Book").each(function () {

        $(".main").append('<div class="book"><div class="title">' + $(this).find("Title").text() + '</div><div class="description">' + $(this).find("Description").text() + '</div><div class="date">Published ' + $(this).find("Date").text() + '</div></div>');
        $(".book").fadeIn(1000);

    });

}

The HTML

The contents of the XML file will be injected into the .main div. Once the XML data is parsed the loading gif is faded out.


<div class="main">
<div align="center" class="loader"><img src="loader.gif" id="load" width="16" height="11" align="absmiddle"/></div>
</div>

<div class="clear"></div>


Recent shares

More tutorials from Papermashup
Comments
10 discussions around Parse XML with jQuery
  1. Miguel says:

    What it be possible to write a loop in here to listen for new elements in the XML? Case: I have users editing a form that generates new XML and if they add a new link it will generate a new node. These are not computer savvy people so they will not have access to the XML.

  2. Laurentb0204 says:

    Hey, I don’t understand but this code don’t work in IE8 and Chrome. I have already tested with another code like this, but again! (http://papermashup.com/parse-xml-with-jquery/). I thought that it compaible with all navigator.
    Anybody have a answer or ideas?
    Thanks

  3. Martin says:

    Muy buena informacion, gracias!!!!

  4. Miguel says:

    What if you run into XML with attributes? I wrote a post about this here

    http://webhole.net/2009/12/16/how-to-read-xml-with-javascript/

  5. Dimo says:

    awesome! just what i was waiting for…

  6. BEBEN says:

    your all article very usefully
    nice to be here for read…thanks
    nice to meet you ^,^

  7. Brian says:

    Hey Ash, awesome post, I have been looking for something like this. Yoink!

    Brian

  8. Atul Kash says:

    Hey Ashley, Thanks for another great article. I guess this could be used for creating a nice gallery. Thank again

  9. Pingback: uberVU - social comments

  10. d13t says:

    Great! This is just what I needed to parse xml from GalleryCMS.

Looking for a registry cleaner to speed up your PC and show a full diagnostics?
Faster surfing with Dish Network High Speed Internet

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in touch.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com you can find details here Or use the contact link below for further advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.