Parse XML with jQuery

I had a client come to me this week with a quick request. His company distributes the same news to their website and their digital media network (they have plasma displays throughout their organization displaying a variety of content from Flash to video to images and text). So, he wants to use the same XML file for both.

Rather than using server side language to do this, which would have been a pain in this instance, I found that jQuery would do the job. 

Here's the skinny: the XML is formatted RSS 2.0 and the page just reads and display title, source, and description. All I needed to do was add jQuery to the page, load up the XML file, retrieve the values, and append the content to a div on the page.

The jQuery code looks like this:

<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script language="javascript">

    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "sample.xml",
            dataType: "xml",
            success: function(xml) {
                $(xml).find('item').each(function(){
                    var title = $(this).find('title').text();
                    var source = $(this).find('source').text();
                    var description = $(this).find('description').text();
                    $('<div class="news_title"></div>').html(title).appendTo('#news_wrap');
                    $('<div class="news_source"></div>').html(source).appendTo('#news_wrap');
                    $('<div class="news_description"></div>').html(description).appendTo('#news_wrap');
                });
            }
        });
    });
</script>

It's pretty straight forward, and I almost don't feel like much of a programmer this was so easy. First I make sure the document is ready, then make an ajax call to get the xml file. I assign a function to handle the success event.

The function then looks for a node matching the find, in the first case "item", and then loops on that.

$(xml).find('item').each(function(){ ... do something ... }

Within the loop I retrieve the data into local vars and then append that data with some html wrapping to the div#news_wrap which is the target div within the page.

It's that simple.

You can see a working example here: http://www.simplyprofound.com/samples/xml_jquery/

 


GeneralPermalink

Name:

Email:

Location:

URL:

Smileys

Remember my personal information

Notify me of follow-up comments?