Reading XML with jQuery

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

<script src="jquery.js" type="text/javascript"></script>

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();
$('<div class="items" id="link_'+id+'"></div>').html('<a href="'+url+'">'+title+'</a>').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();
				$('<div class="items" id="link_'+id+'"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#page-wrap');
				$(this).find('desc').each(function(){
					var brief = $(this).find('brief').text();
					var long = $(this).find('long').text();
					$('<div class="brief"></div>').html(brief).appendTo('#link_'+id);
					$('<div class="long"></div>').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 Responses to Reading XML with jQuery

  1. Pingback: I wrote my first tutorial! : jaredharbour.com

  2. Pingback: links for 2008-09-08 « Brent Sordyl’s Blog

  3. EllisGL

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

  4. Pingback: Weekly Link Post 59 « Rhonda Tipton’s WebLog

  5. Thank you

  6. 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

    Thank you.
    But it doesnt seem to work on firefox

  8. @A developer

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

  9. Hi,

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

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

  11. @Dean

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

  12. what can i do to make it work in IE7?

  13. @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

    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. Thanks a lot.

  16. pm zanetti

    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

  17. Parimah

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

  18. Pingback: CODERS » Blog Roll II

  19. 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(){

  20. 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?

  21. 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]

  22. 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)”)

  23. 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’);

    });
    }
    });
    });

  24. 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.

  25. 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/#

  26. 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.

  27. 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

  28. Stefan

    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.

  29. Suresh

    Hi Dude,

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

  30. 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?

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

  32. 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?

  33. Pingback: Twitter Trackbacks for Reading XML with jQuery | Think2Loud [think2loud.com] on Topsy.com

  34. Thanks, clear and simple examples that helped me!

  35. 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

  36. 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!

  37. Thomas

    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

    • 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.

  38. 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…

  39. Pingback: Blogging Task 8 « Web Application Development Environments INFT215

  40. That’s and good question. I can’t think of a way to do this off the top of my head, but i’m going to look into it.

    You could try taking the xml data and turning it into a JSON object. There are lots of ways to do this, including a jQuery plugin that is out there somewhere.

    Jared

  41. Jared,

    Thank you so much. I will look into JSON.

    Regards,
    Everardo

  42. you’re not going to be able to access that XML without some kind of proxy. JavaScript by itself can’t access cross domain files.

  43. I’ve always found it best to use the full path, but the relative path will work too. It just depends on what you need to accomplish. For example, if you are pulling data for dynamic pages the relative path would be best since you will probably need to include the script on multiple pages.