Read XML File Using Web API

Introduction

This article explains how to read a XML file using the Web API. Here we need to create a XML file and save it in a folder from where the Web API reads the XML and displays the record in the browser. In this tutorial I will create an "Employee.XML" file.

The data of this XML file, when displayed, appears like this:

  1. <?xml version="1.0" ?>  
  2. -<documentelement>-  
  3.     <employee>  
  4.     <id>1</id>  
  5.     <cmp_name>MCN Solutions Pvt Ltd</cmp_name>  
  6.     <address>Noida</address>  
  7.     </employee>-  
  8.     <employee>  
  9.     <id>2</id>  
  10.     <cmp_name>NIIT Limited</cmp_name>  
  11.     <address>Gurgao</address>  
  12.     </employee>-<employee>  
  13.     <id>3</id>  
  14.     <cmp_name>Cipla</cmp_name>  
  15.     <address>Delhi</address>  
  16.     </employee>-<employee>  
  17.     <id>4</id>  
  18.     <cmp_name>Tech Mahindra</cmp_name>  
  19.     <address>Noida</address>  
  20.     </employee>  
  21. </documentelement> 

Step 1

Create the Web API application as in the following:

  • Start Visual Studio 2013.
  • From the Start Window Select "New Project".
  • Select "Installed" -> "Template" -> "Visual C#" -> "Web" -> "Visual Studio 2012" and then select "ASP.NET MVC4 Web Application".

    MVC4 Web Application
  • Click on the "OK" button.
  • From the MVC4 project window select "Web API".

    Web API
  • Click on the "OK" button.

Step 2

Create a model class:

  • In the Solution Explorer.
  • Right-click on the Model Folder.
  • Select "Add" -> "Class".
  • Select "Installed" -> "Visual C#"-> and select "Class".

    Add model Class
  • Click on the "OK" button.

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;   
  5. namespace APIApp.Models  
  6. {  
  7.     public class Employee  
  8.     {  
  9.         public string ID { getset; }  
  10.         public string Cmp_Name { getset; }  
  11.         public string Address { getset; }  
  12.     }  
  13. } 

Step 3

Create an API controller:

  • In the "Solution Explorer".
  • Right-click on the "Controller folder".
  • Select "Add" -> "Controller".
  • Select "API Controller" from the template.

    Add API Controller
  • Click on the "Add" button.

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using APIApp.Models;  
  8. using System.Xml.Linq;  
  9. namespace APIApp.Controllers  
  10. {  
  11.     public class EmployeeController : ApiController  
  12.     {  
  13.         public List<Employee> GetAllEmpoyees()  
  14.         {  
  15.             List<Employee> employees = new List<Employee>();      
  16.             XDocument doc = XDocument.Load("D:\\Mudita\\Employee.xml");  
  17.             foreach (XElement element in doc.Descendants("DocumentElement")  
  18.                 .Descendants("Employee"))  
  19.             {  
  20.                 Employee employee = new Employee();  
  21.                 employee.ID = element.Element("ID").Value;  
  22.                 employee.Cmp_Name = element.Element("Cmp_Name").Value;  
  23.                 employee.Address  = element.Element ("Address").Value;  
  24.                 employees.Add(employee);     
  25.             }  
  26.             return employees;  
  27.         }  
  28.         public Employee GetEmployee(int id)  
  29.         {  
  30.            Employee employee = new Employee();  
  31.            XDocument doc = XDocument.Load("D:\\Mudita\\Employee.xml");  
  32.             XElement element = doc.Element("DocumentElement")  
  33.                                 .Elements("Employee").Elements("ID").  
  34.                                 SingleOrDefault(x => x.Value == id.ToString());  
  35.                        if (element != null)  
  36.             {  
  37.                 XElement parent = element.Parent;  
  38.                 employee.ID =  
  39.                         parent.Element("ID").Value;  
  40.                 employee.Cmp_Name =  
  41.                         parent.Element("Cmp_Name").Value;  
  42.                 employee.Address =  
  43.                         parent.Element("Address").Value;  
  44.                 return employee;  
  45.             }  
  46.             else  
  47.             {  
  48.                 throw new HttpResponseException  
  49.                     (new HttpResponseMessage(HttpStatusCode.NotFound));  
  50.             }  
  51.         }  
  52.     }  
  53. }   

Step 4

Add an Index.cshtml file using the following:

  • In Solution Explorer.

  • Select "Home" -> "Index.cshtml".

    Index file

Add the following code to it:

  1. <div id="body">  
  2.     <section class="content-wrapper main-content clear-fix">  
  3.         <div>  
  4.             <h2>All Employees</h2>  
  5.         </div>  
  6.         <div>  
  7.             <table id="employees" style="border: 1px solid black;"></table>  
  8.         </div>  
  9.     </section>  
  10. </div>  
  11. @section scripts {  
  12.     <script>  
  13.         var apiEmployees = 'api/employee';  
  14.         $(document).ready(function () {  
  15.             // Send an AJAX request  
  16.             var rows = '';  
  17.             $('#employees').empty();  
  18.             $.getJSON(apiEmployees,  
  19.                 function (data) {  
  20.                     $.each(data, function (key, val) {  
  21.                         var employeeURL = apiEmployees + '/' + val.EmployeeID;  
  22.                         rows = rows + '<tr style="border: 1px solid black;"><td>  ' +  
  23.                         '<a style="color: Blue; font-weight:bold; font-size:15px"'  
  24.                            + 'href="' + employeeURL + '">' + val.ID + '</a>' +  
  25.                             '</td><td>' + val.Cmp_Name +  
  26.                             '</td><td>' + val.Address + '</td></tr>';  
  27.                     });  
  28.                     $('#employees').html(rows);  
  29.                 });  
  30.         });  
  31.     </script>  
  32. } 

Step 5

Execute the application:

Record of Employee

Now see the record in XML form.

xml output


Similar Articles