Reading XML with jQuery
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.