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.

Comments

  1. says

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

  2. Kenny says

    Hi,

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

  3. Jared says

    @Dean

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

  4. khautinh says

    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

  5. pm zanetti says

    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

  6. Parimah says

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

  7. says

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

  8. says

    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?

  9. says

    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]

  10. says

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

  11. says

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

    });
    }
    });
    });

  12. Crhis says

    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.

  13. says

    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.

  14. Stefan says

    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.

  15. John says

    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?

  16. says

    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?

  17. Thomas says

    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

    • says

      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.

  18. says

    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…

  19. Jared says

    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

  20. Jared says

    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.

  21. says

    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.

Trackbacks