Cómo leer, parsear y mostrar datos xml en orden aleatorio con jQuery

En este tutorial veremos cómo crear un script de jQuery que lea y parsee un archivo XML, para después mostrar sus datos en orden aleatorio. Diréis, que cosa más rara, ¿cuando voy a utilizar esto? Pues aunque parezca raro, es muy posible que en algún proyecto lo tengas que aplicar bajo demanda de un cliente. Por ejemplo, imaginemos que tenemos 8 tiles, pero solo queremos mostrar 4 en la portada en orden aleatorio y JavaScript es la única opción para hacerlo. ¿A que ya no es tan raro? Claro, debemos ser conscientes de los pros y los contras de todo esto:

Pros

  • Los datos están mejor organizados.
  • Fácil de actualizar. Sólo se necesitas acceder al archivo XML y actualizarlo sin tener que tocar todos los códigos html.

Contras

  • Los robots de los motores de búsqueda no serán capaces de rastrear el contenido, ya que no ejecutan el contenido de JavaScript.
  • El usuario debe tener habilitado Javascript. Bueno, honestamente, este punto no me preocupa mucho. Casi todo el mundo lo tiene habilitado.

Dependiendo de tu proyecto, o de lo importante que sea el SEO para ti, puedes atreverte a hacerlo o no. Mi consejo es, si tienes la opción de hacerlo mediante lenguaje del lado del servidor, hazlo, ya que no tendrás ningún problema con el SEO. Pero, para este caso, vamos a suponer que JavaScript es el último recurso. ¿Ok :-)?

HTML

No vamos a hacer muchas cosas con el HTML en este tutorial. Lo que necesitamos es un elemento con un ID o una clase tal que así:

<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>

Otra sección del HTML es la plantilla HTML que vamos a usar en 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

Tampoco haremos mucho con CSS, puedes dar estilo a los elementos que quieras del HTML. Para lo único que utilizaremos CSS aquí es para que nuestro proyecto luzca bonito, y nada más.

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

Este es el XML de ejemplo que vamos a utilizar. Sencillo y directo.

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

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

Javascript

Bien, esta es la parte principal de todo el tutorial. Básicamente, usamos jQuery para recuperar los datos del archivo XML, después de iterar a través de todos los elementos. Durante el bucle, los enviamos a una función llamada insertHTML(), que recupera los datos del item y los inserta en la plantilla HTML. Después de eso, los asigna a #list.

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();

 

¿Y si tienes una estructura XML distinta?

No pasa nada, si cuentas con una estructura XML diferente, tendrás que modificar lo siguiente:

  • El archivo XML: Lógicamente, en tu caso será distinto.
  • insertHTML(): La función de Javascript para parsear los datos e insertarlos en el HTML

Si tienes un estructura XML distinta, básicamente tendrás que modificar el insertHTML() de Javascript.

Fuente: queness.com

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP