Wednesday, June 6, 2012

LINQ to XML Filter on Element Values


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" />
  </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

    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. 

Search Flipkart Products:
Flipkart.com

3 comments:

Anonymous said...

All life demands struggle. Those who have everything given to them become lazy, selfish, and insensitive to the real values of life. The very striving and hard
work that we so constantly try to avoid is the major building block in the person we are today. See the link below for more info.

values @
www.inspgift.com

williambli92982 said...

Good post. I learn one thing tougher on different blogs everyday. It's going to always be stimulating to read content from different writers and follow a bit of one thing from their store. I’d prefer to use some with the content on my weblog whether or not you don’t mind. Natually I’ll provide you with a hyperlink on your internet blog. Thanks for sharing. online casinos

swedencasino said...

"The author's use of real-life examples and case studies really brought the topic to life. It helped me relate to the subject matter and understand its relevance in today's world."
Iraq tours