September 6th, 2008 by Jared | 28 comments
Welcome to my first of many articles for Think2Loud! Today I thought I’d start with something simple that will lead into several other topics. So here we go, head first into 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.
How well does it go against large XML Files, Say, 5 meg?
Thank you
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”.
Thank you.
But it doesnt seem to work on firefox
@A developer
What version of firefox are you using? The demo works for me in firefox 2 and 3 on OSX.
Hi,
Nice example, completely simple and gets the job done. And it *does* work in Firefox, btw (I’m using v3.0.5).
This works fine in FF, but does not work in IE7.
@Dean
The demo seems to still work for me in IE7 (and everywhere else for that matter), what version are you running?
what can i do to make it work in IE7?
@Raj
Any way you can send me a link, I’ll take a look and see if i can figure out whats going on.
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
Thanks a lot.
@khautinh
check out Using jQuery and XML to Populate a Drop-Down Box
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
Hi
I am dealing with an xml which might be empty.. how can I test before doing the find on it?
Thanks
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(){
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
Jared,
Thank you so much. I will look into JSON.
Regards,
Everardo
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?
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]
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)”)
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’);
});
}
});
});
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.
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/#