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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Services;
- using System.Xml.Linq;
- namespace LINQ.XML
- {
- /// <summary>
- /// Summary description for EmployeeServices
- /// </summary>
- [WebService(Namespace = "http://w3schools.com/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
- // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
- [System.Web.Script.Services.ScriptService]
- public class EmployeeServices : System.Web.Services.WebService
- {
- XElement xelement;
- [WebMethod]
- public string HelloWorld()
- {
- return "Hello World, this is a web service test";
- }
- [WebMethod]
- public List<EmpDetails> getAllEmployees()
- {
- //Load XML Document
- xelement = XElement.Load(Server.MapPath("Employees.xml"));
- //Read all Employee tags
- var EmpElements = xelement.Elements();
- //Create List of EmpDetails
- List<EmpDetails> employees = new List<EmpDetails>();
- //Populate the list with query results
- foreach (var employee in EmpElements)
- {
- employees.Add( new EmpDetails { EmpId=employee.Element("EmpId").Value, EmpName=employee.Element("Name").Value } );
- }
- return employees;
- }
- [WebMethod]
- public List<EmpDetails> getFemaleEmployees()
- {
- List<EmpDetails> females = new List<EmpDetails>();
- //Load XML Document
- xelement = XElement.Load(Server.MapPath("Employees.xml"));
- //Get female employees
- var f_emp = from nm in xelement.Elements("Employee")
- //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
- //let emps= nm.Element("Name").Value //return Name elements instead of Employee
- where nm.Element("Sex").Value == "Female"
- //where nm.Element("Sex").Value == "Female"
- //where (string)nm.Element("Sex") =="Female"
- select nm;
- //Populate the list with query results
- foreach (var employee in f_emp)
- {
- females.Add(new EmpDetails { EmpId = employee.Element("EmpId").Value, EmpName = employee.Element("Name").Value });
- }
- return females;
- }
- [WebMethod]
- public List<EmpDetails> getMaleEmployees(string gender)
- {
- //Create a list of employees
- List<EmpDetails> males = new List<EmpDetails>();
- //Load XML file
- xelement = XElement.Load(Server.MapPath("Employees.xml"));
- //Reads employees only if sex is male
- var m_emp = from emp in xelement.Elements("Employee")
- where emp.Element("Sex").Value == gender
- select emp;
- //Populate the list with query results
- foreach(var employee in m_emp)
- {
- males.Add( new EmpDetails { EmpId = employee.Element("EmpId").Value, EmpName = employee.Element("Name").Value } );
- }
- return males;
- }
- }
- public class EmpDetails
- {
- public string EmpId { get; set; }
- public string EmpName { get; set; }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Xml.Linq;
- namespace LINQ.XML
- {
- public partial class XML_TASKS : System.Web.UI.Page
- {
- XElement xelement;
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- //Bind GridAllEmps as dummy table
- BindColumnToGridview();
- }
- }
- private void BindColumnToGridview()
- {
- DataTable dt = new DataTable();
- dt.Columns.Add("EmpId");
- dt.Columns.Add("EmpName");
- dt.Rows.Add();
- GridAllEmps.DataSource = dt;
- GridAllEmps.DataBind();
- GridAllEmps.Rows[0].Visible = false;
- //Bind GridEmployees
- DataTable dt1 = new DataTable();
- dt1.Columns.Add("Employee ID");
- dt1.Columns.Add("Employee Name");
- dt1.Rows.Add();
- GridEmployees.DataSource = dt1;
- GridEmployees.DataBind();
- GridEmployees.Rows[0].Visible = false;
- }
- }
- }
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:
- $(document).ready(function () {
- //Empty Grid view first
- //$("#GridAllEmps").empty();
- //Test web method only
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "http://localhost:4000/EmployeeServices.asmx/HelloWorld",
- data: "{}",
- dataType: "json",
- success: function (data) {
- $("#txtMsg").val(data.d);
- },
- error: function (result) {
- $("#txtMsg").val("Error!");
- }
- });
- //----------------------------------------------------------------
- //Get Female Employees
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "http://localhost:4000/EmployeeServices.asmx/getFemaleEmployees",
- data: '{}',
- dataType: "json",
- success: function (data) {
- //Iterate through returned data and append it to the grid view
- for (var i = 0; i < data.d.length; i++) {
- $("#GridEmployees").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");
- }
- },
- error: function (result) {
- alert("Error reading the web method getMaleEmployees");
- }
- });
- //-----------------------------------------------------------------
- //call 'getAllEmployees' Web Method to return all employees
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "http://localhost:4000/EmployeeServices.asmx/getAllEmployees",
- data: "{}",
- dataType: "json",
- success: function (data) {
- $("#txtEmps").val(data.d[0].EmpId + " " + data.d[0].EmpName);
- //Iterate through returned data and append it to the grid view
- for (var i = 0; i < data.d.length; i++)
- {
- $("#GridAllEmps").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");
- }
- },
- error: function (result) {
- alert("Error reading the web method getAllEmployees");
- }
- });
- //*****************************
- //On click 'btn_men' , display only men
- $("#btn_men").click(function (e)
- {
- //Empty 'GridAllEmps' to avoid appending to old data
- $("#GridAllEmps").find("tr:gt(0)").remove();
- //Prevent Default behavior 'Post Back'
- e.preventDefault();
- //call 'getAllEmployees' Web Method to return all employees
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "http://localhost:4000/EmployeeServices.asmx/getMaleEmployees",
- data: '{gender:"Male"}' ,
- dataType: "json",
- success: function (data) {
- $("#txtEmps").val(data.d[0].EmpId + " " + data.d[0].EmpName);
- //Iterate through returned data and append it to the grid view
- for (var i = 0; i < data.d.length; i++) {
- $("#GridAllEmps").append("<tr><td>" + data.d[i].EmpId + "</td><td>" + data.d[i].EmpName + "</td></tr>");
- }
- },
- error: function (result) {
- alert("Error reading the web method getMaleEmployees");
- }
- }); //END $.ajax
- }); //END 'btn_men.click
- //*******************
- });
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.
- <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:
Decryption key is given below:
- !ju1LnmV4AYq7QFSL-UGViUIwyvqZhEfRPN1xb81RxXk

kalpesh xxxPosted Jan 17, 2020, 2:50 AM
I had question i had consumed i m using vs 2015 and c# mvc project. I had webservices to which i connected using webreference. now in controller i m consuming that webservice in and output is coming in xml but due to lack of my knowledge i m not able to format data and display same in view from controller help will be appreciated: public ActionResult Index(string ClientCode) { //Pmswebservice.GetClientDataRequestBody clirequest = new Pmswebservice.GetClientDataRequestBody(); //Pmswebservice.GetClientDataResponseBody output = clirequest.ClientCode(ccode.Trim()); //clirequest. ClientReport.GainLoss clientcode = new ClientReport.GainLoss(); string data = clientcode.GetClientData(ClientCode.Trim()).ToString(); XDocument //DataSet objds = new DataSet(); //objds.ReadXml(data); //DataTable dt = new DataTable() ; //dt.ReadXml(data); ViewBag.Reports = data; return View(); }
kalpesh xxxPosted Jan 17, 2020, 2:50 AM
Thanks for your valuable article it provide new insights for learners
Rahul MishraPosted Aug 2, 2018, 1:52 AM
Nice Article
Hadshana KamalanathanPosted Jul 22, 2018, 1:18 AM
Good one..