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

37 comments

Craig
Wed, 3rd August 2011
Great tutorial, very helpful. One problem though, how would I read/display a sub-element of an element? Reply
Kevin Liew Admin
Wed, 3rd August 2011
You should able to use this: item.find('desc subelement').text(); Reply
saqib
Wed, 3rd August 2011
Thanks for sharing such a nice work. Reply
thom morais
Sat, 6th August 2011
i try some like this var img = item.find('content:encoded img').text(); but don´t work :/ Reply
Thomas
Sun, 7th August 2011
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
Sun, 7th August 2011
use this:
var content = $(this).find("content:encoded").text() Reply
Kevin Liew Admin
Sun, 7th August 2011
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
Tue, 9th August 2011
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
Sat, 27th August 2011
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
Sun, 28th August 2011
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
Tue, 13th September 2011
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
Tue, 1st November 2011
Hi,

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

Thanks,
Pallavi Reply
Kevin Liew Admin
Tue, 1st November 2011
Are you sure? I checked it on IE7,8 and 9 again. It works perfectly! Reply
suresh
Thu, 24th November 2011
how can i read xml file through javascript and place it on the image. text from xml should appear on the image. Reply
Danny
Sun, 27th November 2011
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
Mon, 28th November 2011
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
Mon, 28th November 2011
Can you show me the structure of your xml file? Reply
Danny
Tue, 29th November 2011
<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
Tue, 20th December 2011
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
Tue, 20th December 2011
Sorry, I don't get what you mean, do you mean those 3 boxes in the demo page? Reply
TheDude
Tue, 15th May 2012
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
Tue, 15th May 2012
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
Thu, 19th January 2012
Great tutorial! Exactly what I needed for the project I am working on. Thanks. Reply
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
Michal
Sun, 19th October 2014
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

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