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
    Kim Abercrombie
    Carla Adams
    Jay Adams

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);