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

Written by Kevin Liew on 02 Aug 2011
94,005 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
Jesse 13 years ago
is there a way to turn this into reading an RSS feed instead of the XML document?
Reply
Kevin Liew Admin 13 years ago
Hi Jesse, I'm pretty sure you can, RSS feed is XML document. You just need to get the XML path right.
Reply
hoasabi 12 years ago
Hi, great script! How can I put this in a jcarousel for scrolling? Like an image slider with random images every time the page loads and yet scrollable? Thanks!
Reply
gianluca 12 years ago
Hi my code xml this is
<?xml version="1.0" encoding="utf-8"?>
<poemes>


<poeme>
<date>12/11/2011</date>
<category>Amore</category>
<title>Rose simmetrie</title>
<desc>Beltà femminile cha t’innamori sii fatta di vari allori La tua concezione di sensazioni fanno andare in visibilio i romanticoni Non credi nell’amicizia con l’opposto tuoma quando lo ami tu lo vuoi più del tuo stesso io Donna ti dico che la tua volontà assai mi pesa però so che in fondo sii un’opera ben resa Tu non sai cosa sprigioni nella tua decisione nell’unione dei due mondi è una faccenda di ragione Meraviglia del mondo antico e moderno accetta la mia amicizia per amor fraterno</desc>
<tag>Amore, Rose simmetrie, Emozioni, Femminile, Beltà, Volontà, Meraviglia, Mondo antico, Versi, Testo, Parole, Metafora, Dedica</tag>
<link>Scarica file per: Word Pdf Txt</link>
</poeme>

<poeme>
<date>14/11/2011</date>
<category>Amore</category>
<title>Pure emozioni</title>
<desc>Eterno paradiso incontaminato di orchidee Distesa tropicale di spiagge bagnate dal sole Dolce lato dell'animo umano Scultura di bellezza e perfezione Croce e delizia Candido orsacchiotto simbolo di tenerezza e di pace Viso del neonato con i suoi occhi che ti guarda Primo bacio mai scordato Realizzare una tua passione Amore che non muori</desc>
<tag>Amore, Pure, Emozioni, Paradiso, Scultura, Viso nenonato, Passione, Versi, Testo, Parole, Astratto, Sentimento universale</tag>
<link>Scarica file per: Word Pdf Txt</link>
</poeme>

</poemes>

What i write code in js for watch xml
Reply
Jesse 12 years ago
Kevin - this is EXACTLY what I needed. Thank you so much for a fantastic chunk of code!
BTW, is there an easy way to make it refresh with new items (either time based or via a button)?
Reply
Carlos 12 years ago
This looks to be broken with latest jQuery. Any fix?
Reply
Carlos 12 years ago
I'm stumped, when I look at this page's demo in IE 8, it works. When I download and view the sample index.html in IE8 it doesn't work. What's going on? HELP!!!
Reply
Alin 11 years ago
I need to -
display just 'Title' in HMT from XML file and
when I click anyone title then display all information of that title in another HTML page.
plz help me to give your valuable suggestion.

Alin
http://www.alinsworld.com
Reply
Michal 10 years ago
Hi. Brilliant tutorial, thank you.

I have a question. In my xml file elements will be permantent (title, description, url, gallery) except tags. Each element will have different amount of tags. How can i show them?


<item>
<title></title>
<description></description>
<url></url>
<gallery></gallery>
<tags>
<tag></tag>
<tag></tag>
<tag></tag>
<tag></tag>
</tags>
</item>
Reply
Deepak 9 years ago
I want to display xml content of XMLDocument as it is (xml format) inside div tag using jquery.Reason i dont want to manually fetch each node text and then bind that on UI is my xml is more complex.
Reply