Wednesday, June 6, 2012

LINQ to XML Filter on Attribute Values


In this post LINQ to XML Filter on Attribute Values, we shall see how to filter the XML tags based on a specific Attribute 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" />
  </Employee>
  </Employees>

   Now we will parse the XML and get the details of Employees who have a value of Automobile in their Department Attribute.

XElement xEmp = XElement.Load(@"D:\Employees.xml");
var empNames = from emps in xEmp.Elements("Employee")
               where emps.Element("Department").Attribute("Name").Value.Equals("Automobile")
               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: Henry
Age: 65
Department:
Automobile

   Notice that though we had the details of 2 employees in the XML only the details of the Employee with the value Automobile in the Name attribute are 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. 

Search Flipkart Products:
Flipkart.com

No comments: