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

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


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

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

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

36 comments

Andy Web
Mon, 19th March 2012
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
Mon, 19th March 2012
It could be the structure of the XML file is different. You need to adapt this script to your XML file. Reply
Andy
Mon, 19th March 2012
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
Mon, 19th March 2012
that's strange. You can try to use JSON instead. Reply
Rob
Mon, 31st March 2014
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
Jesse
Mon, 21st May 2012
is there a way to turn this into reading an RSS feed instead of the XML document? Reply
Kevin Liew Admin
Tue, 22nd May 2012
Hi Jesse, I'm pretty sure you can, RSS feed is XML document. You just need to get the XML path right. Reply
hoasabi
Fri, 29th June 2012
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
Thu, 12th July 2012
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
Tue, 28th August 2012
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
Fri, 18th January 2013
This looks to be broken with latest jQuery. Any fix? Reply
Carlos
Fri, 1st February 2013
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
Thu, 15th August 2013
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

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement