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

2023-09-02 10:21:47 作者:鸢北

我有一个的XDocument 对象。我想查询使用LINQ元素与一个特定的名字在任何深度。当我使用后代(element_name中的内容),我只得到这是当前级别的直接子元素。我正在寻找的是// element_name中的内容中的XPath相当于...我应该只使用的XPath ,或者是有没有办法使用LINQ方法来做到这一点?谢谢你。

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.

推荐答案

后人应该精美绝伦。这里有一个例子:

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

结果:

&LT;孙子ID =3/&GT;   &LT;孙子ID =4/&GT;

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