LINQ to XML Where condition to filter records

In this example we will check how to apply where condition to filter records in XML by using LINQ.

Example:

Design:


Code Behind (C#):

System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Parse(@" Thomas Executive Accounts 5000 Wills Manager Accounts 24000 Brod Manager Finance 28000 Smith Analyst Finance 21000 "); var res = from emp in xdoc.Root.Elements() where emp.Element("Department").Value == "Accounts" select new { EmployeeName = emp.Element("Name").Value, Designation = emp.Element("Designation").Value, Department = emp.Element("Department").Value, Salary = emp.Element("Salary").Value }; gvXML.DataSource = res; gvXML.DataBind();

Output:

EmployeeName

Designation

Department

Salary

Thomas

Executive

Accounts

5000

Wills

Manager

Accounts

24000