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
- <?xml version="1.0" encoding="utf-8" ?>
- <Employees>
- <Employee>
- <FirstName>Rita</FirstName>
- <LastName>Muller</LastName>
- <Age>25</Age>
- <HireDate>11/24/2011</HireDate>
- </Employee>
- <Employee>
- <FirstName>Martin</FirstName>
- <LastName>Sommer</LastName>
- <Age>31</Age>
- <HireDate>7/15/2007</HireDate>
- </Employee>
- <Employee>
- <FirstName>Paul</FirstName>
- <LastName>Lincoln</LastName>
- <Age>29</Age>
- <HireDate>5/8/2009</HireDate>
- </Employee>
- </Employees>
Step 2
Next on Page Load event of the .cs file add the section of code.
- protected void Page_Load(object sender, EventArgs e) {
- string file = Server.MapPath("Employee.xml");
- XElement element = XElement.Load(file);
- var employees = from employee in element.Descendants("Employee")
- select new {
- FN = employee.Element("FirstName").Value,
- LN = employee.Element("LastName").Value,
- Age = employee.Element("Age").Value,
- HireDate = employee.Element("HireDate").Value,
- };
- GridView1.DataSource = employees;
- GridView1.DataBind();
- }
Step 3
Finally we are in good shape to implement the code inside the .aspx file,
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
- <Columns>
- <asp:BoundField HeaderText="FirstName" DataField="FN" />
- <asp:BoundField HeaderText="LastName" DataField="LN" />
- <asp:BoundField HeaderText="Age" DataField="Age" />
- <asp:BoundField HeaderText="HireDate" DataField="HireDate" />
- </Columns>
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>
Happy learning.