Monday, August 15, 2011

[jQuery] Using jQuery to extract data from XML

jQuery is a wonderful tool for developers for developing dynamic content in the web. Before you can enjoy all wonderful features by it, you must initiate jQuery at the beginning of your web page first. You can download the whole copy to your hosting, or just using Google libraries API.




<script language="Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Assumed that you want to extract the data from a XML file, called "data.xml".

data.xml
<?xml version="1.0" encoding="utf-8"?>
<books>
    <book id="001">
        <title>Book1</title>
        <content>ABC</content>
    </book>
    <book id="002">
        <title>Book2</title>
        <content>DEF</content>
    </book>
</books>

Here is js code for you to extract the data, and display it at result DIV.
<script language="Javascript">
<!--
jQuery(document).ready(function() {

    var dataUrl = "data.xml";

    jQuery.ajax({
        // get the collections XML
        type: "GET",
        url: dataUrl,
        dataType: "xml",
        error: function (request, error) {
            // do this on AJAX error
        },
        success: function(data) {

            jQuery(data).find('book').each(function() {
                var id = jQuery(this).attr('id');
                var title = jQuery(this).find('title').text();
                var content = jQuery(this).find('content').text();

                var htmlString = 'ID:' + id + '<br>' + 'Title:' + title + '<br>' + 'Content:' + content;
                jQuery('<div></div>').html(htmlString).appendTo('#result');

            });

        }
    });

});
//-->
</script>
<div id="result"></div>
Related Posts Plugin for WordPress, Blogger...