24 December 2013

Read an xml file with jQuery/JavaScript

First of all, Making sure you have jQuery included on your page..
<script type="text/javascript" src="http://YourDomain.com/jquery.js" ></script>


And than, Take a look into your XML file, and change script code according you XML format.
My XML file format is like this:-
<item>
 <link>http://paghdarakshay.wordpress.com/</link>
 <title>Code Solution</title>
 <description>Code Solution</description>
</item>



Now, Here is the script to read an XML:-
<script type="text/javascript">
$(document).ready(function(){
 //Asynchronously retrieve the xml file contents
 $.ajax({
  type: "POST",
  url: "sitemap.xml",
  dataType: "xml",
  success: function(xml) { //Upon successful retrieval
   //Iterate through the all the nodes/items
   $(xml).find('item').each(function(e){ //For each item, perform the following
    var id = e;
    var title = $(this).find('title').text(); //Find the child element of "item" called title
    var url = $(this).find('link').text(); //Find the child element of "item" called link
    var description = $(this).find('description').text();
    //Write out a custom link with the values above
    $('<div class="items" id="link_'+id+'"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#page-wrap');
    //Establish the "description" node/element as the this value below, to be referenced fro child nodes/elements
    $('<div class="description"></div>').html(description).appendTo('#link_'+id);
   });
  }
 });
});
</script>


You can also alter the script according to your purpose.
Note:- Make sure your XML file format and jQuery variables are proper...

No comments:

Post a Comment