Get Data From XML Using Web Service And Jquery

Web service and XML data source

In this blog , I am going to show you how to use XML data source using a Web Service. We consume this Web Service from a normal ASPX page, using jQuery script. I reused the code and here is the link.

From the Web Service, we can get all the employees, all female or male employees. In the Server-side code, we use XML file as the data source and we handle the data received from the XML file as XML nodes use LINQ.

Here is the web service code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Xml.Linq;  
  7.   
  8. namespace LINQ.XML  
  9. {  
  10.     /// <summary>  
  11.     /// Summary description for EmployeeServices  
  12.     /// </summary>  
  13.     [WebService(Namespace = "http://w3schools.com/")]  
  14.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  15.     [System.ComponentModel.ToolboxItem(false)]  
  16.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  17.     [System.Web.Script.Services.ScriptService]  
  18.     public class EmployeeServices : System.Web.Services.WebService  
  19.     {  
  20.         XElement xelement;  
  21.   
  22.         [WebMethod]  
  23.         public string HelloWorld()  
  24.         {  
  25.             return "Hello World, this is a web service test";  
  26.         }  
  27.           
  28.         [WebMethod]  
  29.         public List<EmpDetails> getAllEmployees()  
  30.         {              
  31.             //Load XML Document  
  32.             xelement = XElement.Load(Server.MapPath("Employees.xml"));  
  33.   
  34.             //Read all Employee tags  
  35.             var EmpElements = xelement.Elements();  
  36.   
  37.             //Create List of EmpDetails  
  38.             List<EmpDetails> employees = new List<EmpDetails>();  
  39.   
  40.             //Populate the list with query results  
  41.             foreach (var employee in EmpElements)  
  42.             {  
  43.                 employees.Add( new EmpDetails {  EmpId=employee.Element("EmpId").Value, EmpName=employee.Element("Name").Value } );  
  44.             }  
  45.   
  46.             return employees;  
  47.         }  
  48.   
  49. [WebMethod]  
  50.         public List<EmpDetails> getFemaleEmployees()  
  51.         {  
  52.             List<EmpDetails> females = new List<EmpDetails>();  
  53.             //Load XML Document  
  54.             xelement = XElement.Load(Server.MapPath("Employees.xml"));  
  55.   
  56.             //Get female employees  
  57.             var f_emp = from nm in xelement.Elements("Employee")  
  58.                        //from nm in xelement.Descendants("Name") //use this line to get Name elements directly,but dun use it with the condition below; the element Name does not have Sex element  
  59.                        //let emps= nm.Element("Name").Value  //return Name elements instead of Employee  
  60.                        where nm.Element("Sex").Value == "Female"  
  61.                        //where nm.Element("Sex").Value == "Female"  
  62.                        //where (string)nm.Element("Sex") =="Female"  
  63.                        select nm;  
  64.               
  65.             //Populate the list with query results  
  66.             foreach (var employee in f_emp)  
  67.             {  
  68.                 females.Add(new EmpDetails { EmpId = employee.Element("EmpId").Value, EmpName = employee.Element("Name").Value });  
  69.             }  
  70.             return females;             
  71.         }  
  72.   
  73.   
  74.         [WebMethod]  
  75.         public List<EmpDetails> getMaleEmployees(string gender)  
  76.         {  
  77.             //Create a list of employees  
  78.             List<EmpDetails> males = new List<EmpDetails>();  
  79.   
  80.             //Load XML file  
  81.             xelement = XElement.Load(Server.MapPath("Employees.xml"));  
  82.   
  83.             //Reads employees only if sex is male  
  84.             var m_emp = from emp in xelement.Elements("Employee")  
  85.                         where emp.Element("Sex").Value == gender  
  86.                         select emp;  
  87.   
  88.             //Populate the list with query results  
  89.             foreach(var employee in m_emp)  
  90.             {  
  91.                 males.Add( new EmpDetails { EmpId = employee.Element("EmpId").Value, EmpName = employee.Element("Name").Value } );  
  92.             }  
  93.   
  94.             return males;  
  95.         }  
  96.     }  
  97.   
  98.     public class EmpDetails  
  99.     {  
  100.         public string EmpId { getset; }  
  101.         public string EmpName { getset; }  
  102.   
  103.     }  
  104. }  

Note: Do not forget to add the Yellow-highlighted line to allow consuming the Web Service, using the client-side code.

Here, we consume the Web Service form a normal ASPX page, but use jQuery mechanism. In this code, given below, we bind both the grids with tables to enable adding the data from the Server. If a grid is not bound, it cannot be displayed.

aspx code 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Xml.Linq;  
  9.   
  10. namespace LINQ.XML  
  11. {  
  12.     public partial class XML_TASKS : System.Web.UI.Page  
  13.     {  
  14.         XElement xelement;  
  15.         protected void Page_Load(object sender, EventArgs e)  
  16.         {  
  17.             if (!Page.IsPostBack)  
  18.             {  
  19.                 //Bind GridAllEmps as dummy table  
  20.                 BindColumnToGridview();  
  21.             }  
  22.         }  
  23.   
  24.         private void BindColumnToGridview()  
  25.         {  
  26.             DataTable dt = new DataTable();  
  27.             dt.Columns.Add("EmpId");  
  28.             dt.Columns.Add("EmpName");  
  29.             dt.Rows.Add();  
  30.             GridAllEmps.DataSource = dt;  
  31.             GridAllEmps.DataBind();  
  32.             GridAllEmps.Rows[0].Visible = false;  
  33.   
  34.            //Bind GridEmployees  
  35.             DataTable dt1 = new DataTable();  
  36.             dt1.Columns.Add("Employee ID");               
  37.             dt1.Columns.Add("Employee Name");     
  38.             dt1.Rows.Add();  
  39.             GridEmployees.DataSource = dt1;  
  40.             GridEmployees.DataBind();  
  41.             GridEmployees.Rows[0].Visible = false;  
  42.   
  43.   
  44.         }  
  45.   
  46.     }  
  47. }  
In client-side code

HelloWorld method is the only method for testing the data exchange between the Server and the Browser. We use $.ajax method to send and receive the Server data in JSON format.

Consumer - client-side code:
  1. $(document).ready(function () {  
  2.   
  3.     //Empty Grid view first  
  4.     //$("#GridAllEmps").empty();  
  5.   
  6.     //Test web method only  
  7.     $.ajax({  
  8.         type: "POST",  
  9.         contentType: "application/json; charset=utf-8",  
  10.         url: "http://localhost:4000/EmployeeServices.asmx/HelloWorld",  
  11.         data: "{}",  
  12.         dataType: "json",  
  13.         success: function (data) {  
  14.               
  15.             $("#txtMsg").val(data.d);  
  16.               
  17.         },  
  18.         error: function (result) {  
  19.             $("#txtMsg").val("Error!");  
  20.         }  
  21.     });  
  22. //----------------------------------------------------------------  
  23.   
  24. //Get Female Employees  
  25.     $.ajax({  
  26.         type: "POST",  
  27.         contentType: "application/json; charset=utf-8",  
  28.         url: "http://localhost:4000/EmployeeServices.asmx/getFemaleEmployees",  
  29.         data: '{}',  
  30.         dataType: "json",  
  31.         success: function (data) {  
  32.   
  33.             //Iterate through returned data and append it to the grid view  
  34.             for (var i = 0; i < data.d.length; i++) {  
  35.                 $("#GridEmployees").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");  
  36.             }  
  37.         },  
  38.         error: function (result) {  
  39.             alert("Error reading the web method getMaleEmployees");  
  40.         }  
  41.     });  
  42.   
  43. //-----------------------------------------------------------------  
  44.     //call 'getAllEmployees' Web Method to return all employees  
  45.     $.ajax({  
  46.         type: "POST",  
  47.         contentType: "application/json; charset=utf-8",  
  48.         url: "http://localhost:4000/EmployeeServices.asmx/getAllEmployees",  
  49.         data: "{}",  
  50.         dataType: "json",  
  51.         success: function (data) {  
  52.   
  53.             $("#txtEmps").val(data.d[0].EmpId + " " +  data.d[0].EmpName);  
  54.               
  55.             //Iterate through returned data and append it to the grid view  
  56.             for (var i = 0; i < data.d.length; i++)  
  57.             {  
  58.                 $("#GridAllEmps").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");  
  59.             }  
  60.         },  
  61.         error: function (result) {  
  62.             alert("Error reading the web method getAllEmployees");  
  63.         }  
  64.     });  
  65.     //*****************************  
  66.     //On click 'btn_men' , display only men  
  67.     $("#btn_men").click(function (e)  
  68.     {  
  69.         //Empty 'GridAllEmps' to avoid appending to old data  
  70.         $("#GridAllEmps").find("tr:gt(0)").remove();  
  71.   
  72.         //Prevent Default behavior 'Post Back'  
  73.         e.preventDefault();  
  74.   
  75.         //call 'getAllEmployees' Web Method to return all employees  
  76.         $.ajax({  
  77.             type: "POST",  
  78.             contentType: "application/json; charset=utf-8",  
  79.             url: "http://localhost:4000/EmployeeServices.asmx/getMaleEmployees",  
  80.             data: '{gender:"Male"}' ,  
  81.             dataType: "json",  
  82.             success: function (data) {  
  83.   
  84.                 $("#txtEmps").val(data.d[0].EmpId + " " + data.d[0].EmpName);  
  85.   
  86.                 //Iterate through returned data and append it to the grid view  
  87.                 for (var i = 0; i < data.d.length; i++) {  
  88.                     $("#GridAllEmps").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");  
  89.                 }  
  90.             },  
  91.             error: function (result) {  
  92.                 alert("Error reading the web method getMaleEmployees");  
  93.             }  
  94.         });  //END $.ajax  
  95.     });  //END 'btn_men.click  
  96.     //*******************  
  97. });  

Notice: Change the Web Service address, marked by the highlighted lines.

Web.config note

Change the highlighted number from 6 to 5, if you get ISO error.

  1. <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4" compilerOptions="/langversion:5 /nowarn:1659;1699;1701">  

Due to a size limit, I uploaded the project files in the link, given below:  

Click here to download.

Decryption key is given below:

  1. !ju1LnmV4AYq7QFSL-UGViUIwyvqZhEfRPN1xb81RxXk