Fetching XML Data Through Language Integrated Query In C#

Introduction

 
LINQ stands for Language Integrated Query. LINQ was introduced with .NET 3.5 & can be used with C# or Visual Basic to query different data sources.
 
We will see how LINQ works with XML and fetch the corresponding XML data in our Grid.
 
Let's get started.
 
Step 1
 
Add an xml file to your project and add the code below.
 
Here, the xml has three employees with all the details.
 
File Name - Employee.xml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <Employees>  
  3.     <Employee>  
  4.         <FirstName>Rita</FirstName>  
  5.         <LastName>Muller</LastName>  
  6.         <Age>25</Age>  
  7.         <HireDate>11/24/2011</HireDate>  
  8.     </Employee>  
  9.     <Employee>  
  10.         <FirstName>Martin</FirstName>  
  11.         <LastName>Sommer</LastName>  
  12.         <Age>31</Age>  
  13.         <HireDate>7/15/2007</HireDate>  
  14.     </Employee>  
  15.     <Employee>  
  16.         <FirstName>Paul</FirstName>  
  17.         <LastName>Lincoln</LastName>  
  18.         <Age>29</Age>  
  19.         <HireDate>5/8/2009</HireDate>  
  20.     </Employee>  
  21. </Employees>  
Step 2
 
Next on Page Load event of the .cs file add the section of code.
  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     string file = Server.MapPath("Employee.xml");  
  3.     XElement element = XElement.Load(file);  
  4.     var employees = from employee in element.Descendants("Employee")  
  5.     select new {  
  6.         FN = employee.Element("FirstName").Value,  
  7.             LN = employee.Element("LastName").Value,  
  8.             Age = employee.Element("Age").Value,  
  9.             HireDate = employee.Element("HireDate").Value,  
  10.     };  
  11.     GridView1.DataSource = employees;  
  12.     GridView1.DataBind();  
  13. }  
Step 3
 
Finally we are in good shape to implement the code inside the .aspx file,
  1. <html  
  2.     xmlns="http://www.w3.org/1999/xhtml">  
  3.     <head runat="server">  
  4.         <title></title>  
  5.     </head>  
  6.     <body>  
  7.         <form id="form1" runat="server">  
  8.             <div>  
  9.                 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">  
  10.                     <Columns>  
  11.                         <asp:BoundField HeaderText="FirstName" DataField="FN" />  
  12.                         <asp:BoundField HeaderText="LastName" DataField="LN" />  
  13.                         <asp:BoundField HeaderText="Age" DataField="Age" />  
  14.                         <asp:BoundField HeaderText="HireDate" DataField="HireDate" />  
  15.                     </Columns>  
  16.                 </asp:GridView>  
  17.             </div>  
  18.         </form>  
  19.     </body>  
  20. </html>  
Happy learning.
Next Recommended Reading Grouping Data in XML File using LINQ-XML