How to read an xml file with jquery/javascript


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //Perform when the document is ready/loaded/rendered
  2. $(document).ready(function(){
  3. //Asynchronously retrieve the xml file contents
  4. $.ajax({
  5. type: "GET",
  6. url: "sites.xml",
  7. dataType: "xml",
  8. success: function(xml) { //Upon successful retrieval
  9. //Iterate through the all the nodes/items
  10. $(xml).find('site').each(function(){ //For each item, perform the following
  11. //Read each child node and associate the values with a variable
  12. var id = $(this).attr('id'); //Find an attribute within the "site" node/element
  13. var title = $(this).find('title').text(); //Find the child element of "site" called title
  14. var url = $(this).find('url').text(); //Find the child element of "site" called title
  15. //Write out a custom link with the values above
  16. $('<div class="items" id="link_'+id+'"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#page-wrap');
  17. //Establish the "desc" node/element as the this value below, to be referenced fro child nodes/elements
  18. $(this).find('desc').each(function(){
  19. var brief = $(this).find('brief').text();
  20. var long = $(this).find('long').text();
  21. $('<div class="brief"></div>').html(brief).appendTo('#link_'+id);
  22. $('<div class="long"></div>').html(long).appendTo('#link_'+id);
  23. });
  24. });
  25. }
  26. });
  27. });

URL: http://think2loud.com/224-reading-xml-with-jquery/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.