Submit your widget

Useful Reads and parses XML file with jQuery

Created 13 years ago   Views 13415   downloads 2430    Author queness
Useful Reads and parses XML file with jQuery
View DemoDownload
92
Share |

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

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>  

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

<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>';
     
    ..........
    ..........
    ..........

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.

The article source:http://www.queness.com/post/8743/learn-how-to-read-parse-and-display-xml-data-in-random-order-with-jquery