Reading XML with jQuery

The first step is making sure you have jQuery included on your page.

Second, you should check the XML file you are going to read and make sure it’s free of errors. If you are unfamiliar with XML synatax, check out the W3School’s rules on XML syntax. The file I’m using for this example is just a listing of some Web sites I enjoy.

Finally, you just need to tell jQuery to read the file and print out the contents. Start by adding the document.ready function to the page.

$(document).ready(function(){

});


Within the document.ready we start a jQuery ajax request to read the XML file. The ajax request takes four parameters: file type, url, dataType, and success. You’ll see below how these are set to read a file. The important thing to notice is the success parameter. We set it to a function that takes the data the request gets from the XML file.

$.ajax({
        type: "GET",
	url: "sites.xml",
	dataType: "xml",
	success: function(xml) {

	}
});

This is where the fun part comes in. Now that we are reading the XML, we need to find the data written within it and do something with it. We start by reading the returned data and using the find method to get all the nodes that match the text we supply (in this case, “site”), and then use the each function to loop through what the find function give to us.

$(xml).find('site').each(function(){

});

All that’s left is to get the data from that node and print it out. Do this by using the attr function, and the find function to get the text and any attributes on the nodes.

var id = $(this).attr('id');
var title = $(this).find('title').text();
var url = $(this).find('url').text();
$('').html(''+title+'').appendTo('#page-wrap');

Your final code should look something like this:

$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: "sites.xml",
		dataType: "xml",
		success: function(xml) {
			$(xml).find('site').each(function(){
				var id = $(this).attr('id');
				var title = $(this).find('title').text();
				var url = $(this).find('url').text();
				$('').html(''+title+'').appendTo('#page-wrap');
				$(this).find('desc').each(function(){
					var brief = $(this).find('brief').text();
					var long = $(this).find('long').text();
					$('
').html(brief).appendTo('#link_'+id); $('
').html(long).appendTo('#link_'+id); }); }); } }); });

That’s all it takes to read XML with jQuery. Feel free to check out the demo and download the source code.

45 Comments

  1. I wrote my first tutorial! : jaredharbour.com on September 6, 2008 at 7:48 pm

    […] Go check it out, Reading XML with jQuery. […]



  2. links for 2008-09-08 « Brent Sordyl’s Blog on September 8, 2008 at 8:31 am

    […] Reading XML with jQuery head first into reading XML with jQuery. (tags: jquery) […]



  3. EllisGL on September 10, 2008 at 7:09 am

    How well does it go against large XML Files, Say, 5 meg?



  4. Weekly Link Post 59 « Rhonda Tipton’s WebLog on September 12, 2008 at 3:21 pm

    […] Good article on Reading XML with jQuery. […]



  5. mIRC on September 24, 2008 at 4:34 pm

    Thank you



  6. Bud Gibson on October 13, 2008 at 5:34 am

    This is a great, clear example. I’d be interested to see you address namespaces. There’s no real solution for those because of strong browser issues, but there are workable “solutions”.



  7. A developer on December 3, 2008 at 7:32 am

    Thank you.
    But it doesnt seem to work on firefox



  8. Josh on December 3, 2008 at 7:43 am

    @A developer

    What version of firefox are you using? The demo works for me in firefox 2 and 3 on OSX.



  9. Kenny on January 11, 2009 at 8:24 am

    Hi,

    Nice example, completely simple and gets the job done. And it *does* work in Firefox, btw (I’m using v3.0.5).



  10. Dean on January 23, 2009 at 12:37 pm

    This works fine in FF, but does not work in IE7.



  11. Jared on January 29, 2009 at 1:37 pm

    @Dean

    The demo seems to still work for me in IE7 (and everywhere else for that matter), what version are you running?



  12. Raj on February 5, 2009 at 3:21 am

    what can i do to make it work in IE7?



  13. Jared on February 5, 2009 at 8:19 am

    @Raj

    Any way you can send me a link, I’ll take a look and see if i can figure out whats going on.



  14. khautinh on March 6, 2009 at 2:07 pm

    It’s a nice example. How do you read xml data to the dropdown box?
    Ex: I have the xml file below.
    XML file

    math
    Jan 4
    Jan 20

    physic
    Feb 1
    Feb 25



  15. mirc on March 9, 2009 at 3:22 am

    Thanks a lot.



  16. Josh on March 9, 2009 at 7:48 pm


  17. pm zanetti on March 11, 2009 at 5:26 pm

    thanks for this

    if i want to display the data a specific item for example pull the data for site id=”0″, any suggestions on how to do that on a per item basis

    Pz



  18. Parimah on March 12, 2009 at 5:52 pm

    Hi
    I am dealing with an xml which might be empty.. how can I test before doing the find on it?
    Thanks



  19. CODERS » Blog Roll II on March 13, 2009 at 8:51 am

    […] jQuery e iterando con each … y si te quedaste con ganas de más sobre XML y jQuery … Reading XML with jQuery Como leer xml con jQuery desde […]



  20. Everardo on March 23, 2009 at 11:57 am

    Hello,
    Great tutorial! How would you parse the xml if you did not know the structure of the document? I need to parse a file regardless of the structure; show elements, collections, children, etc.

    Thanks,
    Everardo

    $(xml).find(ANYTHING).each(function(){



  21. martin on March 25, 2009 at 1:15 pm

    hey, thanks for this article it really helped!

    one question though, how would you go about adding pagination for the results, say if i only wanted to show 5 items per page?



  22. Vivekanand on March 29, 2009 at 9:16 pm

    This going to help me a lot in my upcoming project, thanks a lot for your valuable effort and keep going…

    Thanks,
    Vivek
    [http://www.developersnippets.com]



  23. Joe Komenda on April 17, 2009 at 1:52 pm

    Thanks for this very clear example. I had to pull a specific item out of an XML file and this worked great, just by adding .find(“item:eq(2)”)



  24. Willem on April 28, 2009 at 12:23 am

    need help, I am trying to utilize this in the code of the site I am working on, and it is not working in safari.

    website page:
    http://payamrajabi.com/progress_w.html

    $(document).ready(function(){
    $.ajax({
    type: “GET”,
    url: “javascript/content.xml”,
    dataType: “xml”,
    success: function(xml) {
    $(xml).find(‘prjct’).each(function(){
    var id = $(this).attr(‘id’);
    var sze = $(this).find(‘sze’).text();
    var img = $(this).find(‘img’).text();
    var lnk = $(this).find(‘lnk’).text();
    var rllsze = $(this).find(‘rllsze’).text();
    $(”).html(‘‘).appendTo(‘#projects’);

    });
    }
    });
    });



  25. Crhis on May 31, 2009 at 10:20 am

    I tested the demo thouroughly on my work station using identical code and it doesn’t work in IE7 7.0.5730.13. At least not on my machine. It does work in Firefox and Safari.



  26. Crhis on May 31, 2009 at 10:35 am

    After some research I found JQuery’s xml function has some shortcomings and doesn’t always work in IE. I found a JQuery plug-in that converts to JSON and seems to work well.

    http://www.fyneworks.com/jquery/xml-to-json/#



  27. Pralyankar on July 4, 2009 at 3:50 am

    Hi.

    I have XML in a variable in JS file and I want to get details for each node of my XML file. Pleas help me. Thanks in advance.



  28. Ben on July 7, 2009 at 6:50 am

    Is it possible to use a file which is hosted on a different server? Everything seems to stop when I try and use http://xboxapi.duncanmackenzie.net/gamertag.ashx?GamerTag=AxelTron



  29. Stefan on July 8, 2009 at 3:44 am

    IE has issues with the way jQuery handles XML on the local filesystem. If you upload the same code on a server it works without a problem.



  30. Suresh on July 22, 2009 at 5:11 am

    Hi Dude,

    Thank you very much. You’ve saved my time.



  31. John on July 28, 2009 at 8:58 pm

    This might seem silly but when you want to access an xml file in your website but in a different folder do you have to specify the complete path or just the relative path from the page with the script?



  32. John on July 29, 2009 at 9:17 am

    I can’t seem to download the source code or view the demo



  33. Balaji on August 26, 2009 at 5:03 pm

    Great article! Thanks for taking the time to explain Reading XML with jQuery. I’ve been thinking about similar topics lately, and it’s good to see that I’m not alone. What do you think about Customizing HTML forms with jQuery?



  34. […] link is being shared on Twitter right now. @budgibson, an influential author, said Have conquered xml […]



  35. Atea Webdevelopment & Search Engine Optimization on September 4, 2009 at 2:55 pm

    Thanks, clear and simple examples that helped me!



  36. ysatech on October 10, 2009 at 12:15 pm

    thanks. I have put together your tutorial with a simple slide show. http://blog.ysatech.com/post/2009/10/08/JQuery-slideshow-with-XML.aspx



  37. Peter Ellis on October 15, 2009 at 12:53 pm

    There is a great guide for anyone trying to process an RSS/XML feed using JQuery and is running into problems e.g. no data being returned…or so it seems..

    http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html

    In short we wrote a PHP file which got the feed for us acting much like a proxy! Turned out that Firefox was preventing JS from making the call due to Firerfox’s security settings!

    Hope this helps!



  38. Thomas on October 16, 2009 at 1:44 pm

    Thanks for the superb article and the code!, i need a suggestion, I am using a search box with the results coming from a ajax response as xml, should i use json and read it using jquery or directly I can read xml using jquery, which is faster? please advise.

    Thanks in advance
    Thomas



    • Jared on October 16, 2009 at 2:07 pm

      You should feel free to use jQuery to read the XML if that’s your only option, but if you are looking to make your javascript quick and streamlined json is the way to go. This is a great topic for a new post, which i’ve been neglecting for about a month now. Check back in a few hours I could have something up.



  39. Orbith on October 19, 2009 at 2:21 am

    I have a large data in xml file.
    sample:

    content here

    I have thousands of this in my xml..
    Need help how to apply pagination on this…



  40. […] http://think2loud.com/reading-xml-with-jquery/ – How to read the XML with Jquery best example of […]