LINQ to XML: Retrieve an XML element by its attribute value

For this tutorial I will be using the following Sample.xml file



  
    Gustavo Achong
    7/31/1996
  
  
    Kim Abercrombie
    12/12/1997
  
  
    Carla Adams
    2/6/1998
  
  
    Jay Adams
    2/6/1998
  

Create an XDocument object and load the Sample.xml data into the object.

XDocument customers = XDocument.Load(@"Data\Sample.xml");

The attribute we are interested in is id but first we need to drill down to the employee elements and then check each employee element to ensure it’s id attribute isn’t null and to see if it matches our value. When there is a match it selects it.

var customerById = (from customer in customers.Descendants("employee")
                                let xAttribute = customer.Attribute("id")
                                where xAttribute != null && xAttribute.Value.Equals("8")
                                select customer);