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

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. namespace LINQ.XML
  10. {
  11. public partial class XML_TASKS : System.Web.UI.Page
  12. {
  13. XElement xelement;
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. if (!Page.IsPostBack)
  17. {
  18. //Bind GridAllEmps as dummy table
  19. BindColumnToGridview();
  20. }
  21. }
  22. private void BindColumnToGridview()
  23. {
  24. DataTable dt = new DataTable();
  25. dt.Columns.Add("EmpId");
  26. dt.Columns.Add("EmpName");
  27. dt.Rows.Add();
  28. GridAllEmps.DataSource = dt;
  29. GridAllEmps.DataBind();
  30. GridAllEmps.Rows[0].Visible = false;
  31. //Bind GridEmployees
  32. DataTable dt1 = new DataTable();
  33. dt1.Columns.Add("Employee ID");
  34. dt1.Columns.Add("Employee Name");
  35. dt1.Rows.Add();
  36. GridEmployees.DataSource = dt1;
  37. GridEmployees.DataBind();
  38. GridEmployees.Rows[0].Visible = false;
  39. }
  40. }
  41. }
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. //Empty Grid view first
  3. //$("#GridAllEmps").empty();
  4. //Test web method only
  5. $.ajax({
  6. type: "POST",
  7. contentType: "application/json; charset=utf-8",
  8. url: "http://localhost:4000/EmployeeServices.asmx/HelloWorld",
  9. data: "{}",
  10. dataType: "json",
  11. success: function (data) {
  12. $("#txtMsg").val(data.d);
  13. },
  14. error: function (result) {
  15. $("#txtMsg").val("Error!");
  16. }
  17. });
  18. //----------------------------------------------------------------
  19. //Get Female Employees
  20. $.ajax({
  21. type: "POST",
  22. contentType: "application/json; charset=utf-8",
  23. url: "http://localhost:4000/EmployeeServices.asmx/getFemaleEmployees",
  24. data: '{}',
  25. dataType: "json",
  26. success: function (data) {
  27. //Iterate through returned data and append it to the grid view
  28. for (var i = 0; i < data.d.length; i++) {
  29. $("#GridEmployees").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");
  30. }
  31. },
  32. error: function (result) {
  33. alert("Error reading the web method getMaleEmployees");
  34. }
  35. });
  36. //-----------------------------------------------------------------
  37. //call 'getAllEmployees' Web Method to return all employees
  38. $.ajax({
  39. type: "POST",
  40. contentType: "application/json; charset=utf-8",
  41. url: "http://localhost:4000/EmployeeServices.asmx/getAllEmployees",
  42. data: "{}",
  43. dataType: "json",
  44. success: function (data) {
  45. $("#txtEmps").val(data.d[0].EmpId + " " + data.d[0].EmpName);
  46. //Iterate through returned data and append it to the grid view
  47. for (var i = 0; i < data.d.length; i++)
  48. {
  49. $("#GridAllEmps").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");
  50. }
  51. },
  52. error: function (result) {
  53. alert("Error reading the web method getAllEmployees");
  54. }
  55. });
  56. //*****************************
  57. //On click 'btn_men' , display only men
  58. $("#btn_men").click(function (e)
  59. {
  60. //Empty 'GridAllEmps' to avoid appending to old data
  61. $("#GridAllEmps").find("tr:gt(0)").remove();
  62. //Prevent Default behavior 'Post Back'
  63. e.preventDefault();
  64. //call 'getAllEmployees' Web Method to return all employees
  65. $.ajax({
  66. type: "POST",
  67. contentType: "application/json; charset=utf-8",
  68. url: "http://localhost:4000/EmployeeServices.asmx/getMaleEmployees",
  69. data: '{gender:"Male"}' ,
  70. dataType: "json",
  71. success: function (data) {
  72. $("#txtEmps").val(data.d[0].EmpId + " " + data.d[0].EmpName);
  73. //Iterate through returned data and append it to the grid view
  74. for (var i = 0; i < data.d.length; i++) {
  75. $("#GridAllEmps").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");
  76. }
  77. },
  78. error: function (result) {
  79. alert("Error reading the web method getMaleEmployees");
  80. }
  81. }); //END $.ajax
  82. }); //END 'btn_men.click
  83. //*******************
  84. });

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