Export (0) Print
Expand All

How to: Find Elements with a Specific Attribute (XPath-LINQ to XML)

Sometimes you want to find all elements that have a specific attribute. You are not concerned about the contents of the attribute. Instead, you want to select based on the existence of the attribute.

The XPath expression is:


The following code selects just the elements that have the Select attribute.

XElement doc = XElement.Parse(
    <Child2 Select='true'>2</Child2>
    <Child4 Select='true'>4</Child4>

// LINQ to XML query
IEnumerable<XElement> list1 =
    from el in doc.Elements()
    where el.Attribute("Select") != null
    select el;

// XPath expression
IEnumerable<XElement> list2 =

if (list1.Count() == list2.Count() &&
        list1.Intersect(list2).Count() == list1.Count())
    Console.WriteLine("Results are identical");
    Console.WriteLine("Results differ");
foreach (XElement el in list1)

This example produces the following output:

Results are identical
<Child2 Select="true">2</Child2>
<Child4 Select="true">4</Child4>
© 2015 Microsoft