Menu ▼

Previous Next

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 :

<div>

    <asp:GridView ID="gvXML" runat="server" GridLines="Both" CellPadding="5">

    </asp:GridView>

</div>


Code Behind (C#) :

System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Parse(@"

<Employees>

    <Employee>

        <Name>Thomas</Name>

        <Designation>Executive</Designation>

        <Department>Accounts</Department>

        <Salary>5000</Salary>

    </Employee>

    <Employee>

        <Name>Wills</Name>

        <Designation>Manager</Designation>

        <Department>Accounts</Department>

        <Salary>24000</Salary>

    </Employee>

    <Employee>

        <Name>Brod</Name>

        <Designation>Manager</Designation>

        <Department>Finance</Department>

        <Salary>28000</Salary>

    </Employee>

    <Employee>

        <Name>Smith</Name>

        <Designation>Analyst</Designation>

        <Department>Finance</Department>

        <Salary>21000</Salary>

    </Employee>

</Employees>

");

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 :
EmployeeNameDesignationDepartmentSalary
ThomasExecutiveAccounts5000
WillsManagerAccounts24000
Previous Next




Search dotnetlearners.com