C# – Query an XDocument for elements by name at any depth

clinqlinq-to-xmlnetxml

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. I'm looking for the equivalent of "//element_name" in XPath…should I just use XPath, or is there a way to do it using LINQ methods?

Best Answer

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