按名称在任何深度查询元素的 XDocument

问题描述:

我有一个 XDocument 对象.我想使用 LINQ 在任何深度查询具有特定名称的元素.

I have an XDocument object. I want to query for elements with a particular name at any depth using LINQ.

当我使用 Descendants(element_name") 时,我只获取当前级别的直接子元素.我正在寻找等效的//element_name"在 XPath 中...我应该只使用 XPath,还是有办法使用 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?

后代应该可以正常工作.举个例子:

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

结果: