Read and Process XML using jQuery Ajax

While working on my current project, for one of my requirement I need to read and process the XML file using jQuery and Ajax. The actual XML file was very huge and I can't share. So in this post, I will show you how to process XML file with jQuery and Ajax.

Related Post:

Below is the sample XML file that we will be using for the demo.The XML file is having list of books with Title and Publisher as 2 XML node with every book.

//Code Starts
<?xml version="1.0" encoding="utf-8" ?>
<BookList>
  <Book>
     <Title>jQuery: Novice to Ninja</Title>
     <Publisher>Site point</Publisher>
  </Book>
  <Book>
     <Title>Learning jQuery</Title>
     <Publisher>PACKT</Publisher>
  </Book>
  <Book>
     <Title>Head First jQuery</Title>
     <Publisher>O'Reilly</Publisher>
  </Book>
  <Book>
     <Title>jQuery UI 1.8</Title>
     <Publisher>PACKT</Publisher>
  </Book>
</BookList>
//Code Ends

Now, to process the XML using jQuery, below is the idea to how to do it..

  • Declare a div which will be used to show the XML content.
  • As the display will be in the list so append the UL to the div element.
  • Call the ajax method to process the xml file.
  • Set HTTP request type to "GET" and also provide the name of XML file in url.
  • Set the datatype to "xml".
  • We also need to define a callback functions, which gets called when request is successful or if some error occurred.
  • So when success callback is called then loop through the xml content.
  • Get the node value for "Title" and "Publisher" and append it to the div.
  • Define error callback to handle the error.

So here is the complete jQuery code.

//Code Starts
$(document).ready(function(){
  $("#dvContent").append("<ul></ul>");
  $.ajax({
    type: "GET",
    url: "BookList.xml",
    dataType: "xml",
    success: function(xml){
    $(xml).find('Book').each(function(){
      var sTitle = $(this).find('Title').text();
      var sPublisher = $(this).find('Publisher').text();
      $("<li></li>").html(sTitle + ", " + sPublisher).appendTo("#dvContent ul");
    });
  },
  error: function() {
    alert("An error occurred while processing XML file.");
  }
  });
});
//Code Ends

And below is the output:

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...