Wednesday, 21 October 2015

Read XML using jQuery Ajax

Below is the sample XML file that we will be using for the demo.The XML file is having list of Contacts with Name and PhoneNumber as 2 XML node with every Contact. 

XML File :- 


<?xml version="1.0" encoding="utf-8"?>
<ContactList>
<Contact>
<Name>Jitendra Gangwar</Name>
<PhoneNumber>1234567890</PhoneNumber>
</Contact>
<Contact>
<Name>Suraj Sharma</Name>
<PhoneNumber>1234567890</PhoneNumber>
</Contact>
<Contact>
<Name>Arun Kumar</Name>
<PhoneNumber>9876543210</PhoneNumber>
</Contact>
<Contact>
<Name>Dhirendra Kumar</Name>
<PhoneNumber>9512121210</PhoneNumber>
</Contact>

</ContactList>

Now we are going to process the XML using jQuery
  • 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.
jQuery code:-

<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "ContactList.xml",
dataType: "xml",
success: function(xml){
$(xml).find('Contact').each(function(){
var sName = $(this).find('Name').text();
var sPhoneNumber = $(this).find('PhoneNumber').text();
$("<li></li>").html(sName + ", " + sPhoneNumber).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>

Complete Source Code : - 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Process XML using jQuery</title>
<script src="Scripts/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "ContactList.xml",
dataType: "xml",
success: function(xml){
$(xml).find('Contact').each(function(){
var sName = $(this).find('Name').text();
var sPhoneNumber = $(this).find('PhoneNumber').text();
$("<li></li>").html(sName + ", " + sPhoneNumber).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
<style type="text/css">
body
{
font-family : Arial;
font-size : 10pt;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
</body>
</html>

OutPut : -

No comments:

Post a Comment