Learn How to Read, Parse and Display XML Data in Random Order with jQuery

Written by Kevin Liew on 02 Aug 2011
92,948 Views • Tutorials

Introduction

This tutorial will guide you how to build a jQuery script that reads and parses XML file and display data in random order. I made this because I believe some of us might get this kind of request from clients. Eg, load the frontpage promotional tiles randomly among 8 tiles but display only 4 of them and JavaScript is the only option to do it. However, one should aware the pros and cons of this approach:

Pros
  • Better organize of data. Data is stored in XML file instead of hardcoded in web page.
  • Easy to update. You just need the access to XML file and update it without have to go through all the html codes.
Cons
  • SEO concern. Search engine bots/spiders will not able to see the content, because they don't run JavaScript content.
  • Javascript support. Well, honestly, I'm not worry about this one.

Depend on your project, or how important SEO is to you, some people don't really care about the drawback of this method. My advise is, if you have the option to do it with server side language, just do it, you won't have SEO issue. But, in this case, let's just assume Javascript is the last resort. :) You can check out the demo:

Learn How to Read, Parse and Display XML Data in Random Order with jQuery

HTML

We won't do much with HTML in this tutorial. What you need is an element with ID or Class like below:

<div id="list">
<!-- XML data to be appended in here -->
</div>	
<div class="item">
    <a href="#"><img data-src="image.gif" alt="Title"><span>Title</span></a>
    <p>Description</p>
</div>
<div id="list">
<!-- XML data to be appended in here -->
</div>	
<div class="item">
    <a href="#"><img data-src="image.gif" alt="Title"><span>Title</span></a>
    <p>Description</p>
</div>

Another section of HTML is the HTML template that we use in the Javascript:

<div id="list">
<!-- XML data to be appended in here -->
</div>	
<div class="item">
    <a href="#"><img data-src="image.gif" alt="Title"><span>Title</span></a>
    <p>Description</p>
</div>
<div id="list">
<!-- XML data to be appended in here -->
</div>	
<div class="item">
    <a href="#"><img data-src="image.gif" alt="Title"><span>Title</span></a>
    <p>Description</p>
</div>

CSS

We don't do much with CSS too, you can style it whatever you want. Below is the CSS we used in this tutorial, just make sure the demo look nice.

body {
	font-size:75%; 
	margin:0; 
	padding:0; 
	font-family:arial; 
	color:#333
}
#list {
	width:660px; 
	margin:0 auto;
}
#list .item {
	width:200px; 
	float:left; 
	margin:10px;
}
#list .item a {
	font-weight:bold; 
	color:#333; 
	text-decoration:none; 
	outline:0
}
#list .item a:active, #list .item a:hover {
	color:#25c8f1;
}
#list .item a img {
	width:190px;
	height:120px; 
	border:5px solid #eee
}
#list .item a img:hover {
	border:5px solid #25c8f1;
}
#list .item a span {
	padding:0 5px; 
	display:block;
}
#list .item p {
	margin:5px 0 0 0; 
	padding:0 5px;
}

XML

This is a sample XML file that we use. Simple and straight forward.

<?xml version="1.0" encoding="utf-8" ?>
<items>

	<item>
		<url>.......</url>
		<image>.......</image>		
		<title>.......</title>
		<desc>......</desc>
	</item>		
	
	......
</items>

Javascript

Alright, this is the main part of the entire tutorial. Basically, we use jQuery to retrieve data from XML file, after that loop through all the items. During the loop, we send it to a function call insertHTML() which retrieve the data in the item and embed them into a HTML template. After that, append it to #list.

I have put inline comments in most sections to make sure it's easy to understand.

XMLLIST = {

	//general settings
	xml: 'data.xml?' + Math.random(0,1), //solve ie weird caching issue
	display: '3', //number of items to be displayed
	random: true, //display randomly {true|false}
	appendTo: '#list', //set the id/class to insert XML data
	
	init: function () {
	
		//jQuery ajax call to retrieve the XML file
		$.ajax({
			type: "GET",
	    	url: XMLLIST.xml,
	   		dataType: "xml",	   		
	   	 	success: XMLLIST.parseXML
	  	});	
	
	}, // end: init()
	
	parseXML: function (xml) {
	
		//Grab every single ITEM tags in the XML file
		var data = $('item', xml).get();
		//Allow user to toggle display randomly or vice versa
		var list = (XMLLIST.random) ? XMLLIST.randomize(data) : data;
		var i = 1;
		
		//Loop through all the ITEMs
		$(list).each(function () {
			
			//Parse data and embed it with HTML
			XMLLIST.insertHTML($(this));			

			//If it reached user predefined total of display item, stop the loop, job done.
			if (i == XMLLIST.display) return false;
			i++;
		});

	
	}, // end: parseXML()

	insertHTML: function (item) {

		//retrieve each of the data field from ITEM
		var url = item.find('url').text();
		var image = item.find('image').text();
		var title = item.find('title').text();
		var desc = item.find('desc').text();
		var html;
		
		//Embed them into HTML code
		html = '<div class="item">';
		html += '<a href="' + url + '"><img data-src="' + image + '" alt="' + title + '" />';
		html += '<span>' + title + '</span></a>';
		html += '<p>' + desc + '</p>';
		html += '</div>';
		
		//Append it to user predefined element
		$(html).appendTo(XMLLIST.appendTo);
		
	}, // end: insertHTML()

    
	randomize: function(arr) {
  		
  		//randomize the data
  		//Credit to JSFromHell http://jsfromhell.com/array/shuffle
	    for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		    return arr;
  
  	} // end: randomize()    
  	

}

//Run this script
XMLLIST.init();

Hey Dude, I have a different XML structure!

Sure you do, if you have a different XML structure, you need to change the following thing:

  • XML File: Well, you definitely need to change it
  • insertHTML(): a function in the Javascript to parse the data and insert it into HTML

If you have a different XML strucutre, you will need to modify the insertHTML() in Javascript.

parseXML: function (xml) {

	//You need to change "item" to your own tag. 
	var data = $('item', xml).get();


	..........
	..........
	..........


insertHTML: function (item) {

	//If you refer back to the XML structure above, this retrieve all data of each item.
	//Feel free to change it and add new data
	var url = item.find('url').text();
	var image = item.find('image').text();
	var title = item.find('title').text();
	var desc = item.find('desc').text();
	var html;
	
	//This is the HTML template we use, feel free to change it as well.
	html = '<div class="item">';
	html += '<a href="' + url + '"><img data-src="' + image + '" alt="' + title + '" />';
	html += '<span>' + title + '</span></a>';
	html += '<p>' + desc + '</p>';
	html += '</div>';
	
	..........
	..........
	..........
	

Conclusion

This tutorial is aiming to demonstrate how to read and parse XML file with jQuery and display random XML result. Well, it's not the best approach but in some cases, this could be the only way to achieve it, especially when you have limited access to the website. Drop me a comment if you have any question. I hope you enjoy it and please help me to spread this. :)

Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

38 comments
Craig 13 years ago
Great tutorial, very helpful. One problem though, how would I read/display a sub-element of an element?
Reply
Kevin Liew Admin 13 years ago
You should able to use this: item.find('desc subelement').text();
Reply
saqib 13 years ago
Thanks for sharing such a nice work.
Reply
thom morais 13 years ago
i try some like this var img = item.find('content:encoded img').text(); but don´t work :/
Reply
Thomas 13 years ago
how i display this xml

<rss version="2.0">
<channel>
<item>
<content:encoded>
<![CDATA[ <img class=" " title=" " src="" width="" height="" /> ]]>
</content:encoded>
</item>
</channel>
</rss>

exemple please :D
Reply
Kevin Liew Admin 13 years ago
use this:
var content = $(this).find("content:encoded").text()
Reply
Kevin Liew Admin 13 years ago
You can't use item.find('content:encoded img').text(); because img is not part of the DOM structure, it's classified as data because it's wrapped by CDATA.
Reply
david 13 years ago
great post, but never really liked xml when I had to use it, much simpler when I used an xml editor like http://www.liquid-technologies.com/xml-editor.aspx, certainly saved my many hours in coding time.
Reply
foong 13 years ago
Nice post. But I have a problem. I wanted to put 2 blocks of the xml parser on a page (2 x readxml.js) one on the top of the page and the other at the bottom of the page. It will end up the final 2 rows appear at the last block. How do we resolve this?
Reply
Kevin Liew Admin 13 years ago
This example is for an instance. However, there are two solutions,
1. Duplicate the script, search and replace XMLLIST to something else in the duplicated script. Quick, easy but dirty.
2. Edit the script to parse two different xml. This would be more complicated.
Reply
Daniel 13 years ago
Super cool demo and script! But sadly I experience loading problems with IE7 sometimes it's ok, bu often it loads first after 2nd refresh of the page - any ideas?
Reply
Pallavi Zanje 12 years ago
Hi,

This example not working for IE version. Please tell me solution.

Thanks,
Pallavi
Reply
Kevin Liew Admin 12 years ago
Are you sure? I checked it on IE7,8 and 9 again. It works perfectly!
Reply
suresh 12 years ago
how can i read xml file through javascript and place it on the image. text from xml should appear on the image.
Reply
Danny 12 years ago
Hey, great tutorial! Exactly what im looking for for a project im working on! Having trouble getting it to work with my xml though. Im running my HTML through a JSP would this have anything to do with why it wont load for me or could it be that my xml file is too large?
Reply
Danny 12 years ago
Finally figured out what was wrong and have it loading my xml randomly but cant figure out how to load my images as they are stored in a seperate folder. Have you any idea how i reference the jpg files?
Reply
Kevin Liew Admin 12 years ago
Can you show me the structure of your xml file?
Reply
Danny 12 years ago
<cds>
<cd>
<title>Moon Safari</title>
<artist>Air</artist>
<genre>Electronic</genre>
<album_cover>moonsafari.jpg</album_cover>
<price>10.90</price>
<year>1998</year>
</cd>
</cds>

Obviously there are more elements but just to show the structure...

So far i have got the information (title and artist) displaying randomly as the page is reloaded, in IE8 it shows the broken link icon where the image is meant to be displayed but in Firefox it dosnt even give me this, it just shows the ALT text?
Reply
Yoff 12 years ago
Great script, exactly what I need. Just can't figure out how to display 2 elements per row instead of 3.
Reply
Kevin Liew Admin 12 years ago
Sorry, I don't get what you mean, do you mean those 3 boxes in the demo page?
Reply
TheDude 12 years ago
Hi Kevin,

I've got the same problem as Yoff, in FireFox it works perfectly but not on IE8...what can be the problem?
Reply
Kevin Liew Admin 12 years ago
Yoff was having layout issue i think, if you had the same thing.. I think you just have to set the width:

#list {
width:420px;
margin:0 auto;
}
Reply
Lisa Noble 12 years ago
Great tutorial! Exactly what I needed for the project I am working on. Thanks.
Reply
Andy Web 12 years ago
I have tried to get this to work in a Wordpress Theme but it just will not display the contents of the xml file, any ideas would be great help please? It works on a site as the files supplied just great :) But want to use in a Wordpress Theme :)
Reply
Kevin Liew Admin 12 years ago
It could be the structure of the XML file is different. You need to adapt this script to your XML file.
Reply
Andy 12 years ago
Hi Kevin, I haven't changed anything with the files I have simply added your files and calls in the header exactly the same. Wordpress hjust seems to be ignoring everything. I think it has something to do with the way the core Wordpress handles xml and rss. After reading around and looking at plugins for reading xml its becoming apparent xml is not for the weak minded :) I think I may look into using the same techniques to render but use a csv file apparently they are less stubborn.
Reply
Kevin Liew Admin 12 years ago
that's strange. You can try to use JSON instead.
Reply
Rob 10 years ago
Do you have any suggestions/examples in using json for this, I have a similar wordpress problem. I did not amend the code, just added to a test site as is.
Reply