In this post LINQ to XML Filter on Element Values, we
shall see how to filter the XML tags based on a specific element value. In the
post LINQ to XML parse XML Elements,
we saw how to extract values from all elements, here we shall see on how get
the values of elements after applying a filter.
Assume that we have the following XML fragment
<Employees>
<Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
</Name>
<Age>65</Age>
<Department Name="Automobile" />
</Employee>
<Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<Department Name="Software" />
<Department Name="Software" />
</Employee>
</Employees>
Now
we will parse the XML and get the details of Employees whose age is 55.
XElement xEmp = XElement.Load(@"D:\Employees.xml");
var empNames = from
emps in xEmp.Elements("Employee")
where
emps.Element("Age").Value.Equals("55")
select
emps;
Response.Write("Employee Count: " + empNames.Count() + "</br> "</br>");
foreach (XElement
empDetails in empNames)
{
Response.Write("Name:
" + empDetails.Element("Name").Element("FirstName").Value + "</br>");
Response.Write("Age:
" + empDetails.Element("Age").Value
+ </br>");
Response.Write("Department:
" + empDetails.Element("Department").Attribute("Name").Value + </br> </br>");
}
When
this code is executed, the output will be
Employee Count: 1
Name: Bill
Age: 55
Department: Software
Name: Bill
Age: 55
Department: Software
Notice that though we had the details of 2
employees in the XML only the details of the Employee with an Age of 55 is
displayed in the Output, the LINQ query has applied a filter on the XML and
displays only the filtered results.
That’s
it we have filtered an XML fragment using LINQ Query and displayed the filtered
results.