Javascript for reading from an xml file: for dummies.

This script uses jquery to do this. Found initial post at: http://think2loud.com/reading-xml-with-jquery/

Remember, this script works ONLY if the html and xml are on the SAME DOMAIN.

If you’re looking for a solution that works cross-domain, CLICK HERE.

Step 1: Include the following script on your page:

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

Step 2: Add the following snippet of code on the page (description below):

$(document).ready(function(){
$.ajax({
type: “GET”,
url: “contestdata.xml”,
dataType: “xml”,
url: “contestdata.xml”,

$(xml).find(‘item’).each(function(i){
if(i <= “7”) {
var title = $(this).find(‘title’).text();
var url = $(this).find(‘link’).text();
var thumbnail = $(this).find(‘thumbnail’).text();
$(‘<li></li>’).html(‘<a href=”‘+url+'”><img width=”112″ height=”85″ border=”0″ alt=”” src=”‘+thumbnail+'”></a><h5><a href=”‘+url+'”>’+title+'</a></h5>’).appendTo(‘#entry-display’);
}
});
}
});
});

What the script is doing:

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

});

B) 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.

$.ajax({
type: “GET”,
url: “contestdata.xml”,
dataType: “xml”,
success: function(xml) {

}
});

C) Now that we are reading the XML, we need to find the data 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, and then use the each function to loop through what the find function give to us. You can pass i to the function to loop through the number of items. In the example about, I needed to display only 8 entries.

$(xml).find(‘item’).each(function(i){

});

D) Now get the data from the nodes 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 title = $(this).find(‘title’).text();
var url = $(this).find(‘link’).text();
var thumbnail = $(this).find(‘thumbnail’).text();
$(‘<li></li>’).html(‘<a href=”‘+url+'”><img width=”112″ height=”85″ border=”0″ alt=”” src=”‘+thumbnail+'”></a><h5><a href=”‘+url+'”>’+title+'</a></h5>’).appendTo(‘#entry-display’);

Step 3: Add the css to apply styles to this data.
I included my css file on the page:

<link rel=”stylesheet” type=”text/css” media=”all” href=”style.css” />

Step 4: We’re done!

CLICK HERE TO VIEW THE EXAMPLE
CLICK HERE TO DOWNLOAD THE WORKING EXAMPLE
Please note, that you’ll need to view this over a server for it to work.