Query an XDocument for elements by name at any depth

Rich picture Rich · Feb 19, 2009 · Viewed 256.9k times · Source

I have an XDocument object. I want to query for elements with a particular name at any depth using LINQ. When I use Descendants("element_name"), I only get elements that are direct children of the current level. What I'm looking for is the equivalent of "//element_name" in XPath...should I just use XPath, or is there a way to do it using LINQ methods? Thanks.

Answer

Jon Skeet picture Jon Skeet · Feb 19, 2009

Descendants should work absolutely fine. Here's an example:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string xml = @"
<root>
  <child id='1'/>
  <child id='2'>
    <grandchild id='3' />
    <grandchild id='4' />
  </child>
</root>";
        XDocument doc = XDocument.Parse(xml);

        foreach (XElement element in doc.Descendants("grandchild"))
        {
            Console.WriteLine(element);
        }
    }
}

Results:

<grandchild id="3" />
<grandchild id="4" />