按名称在任何深度查询元素的 XDocument [英] Query an XDocument for elements by name at any depth

查看:30
本文介绍了按名称在任何深度查询元素的 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);
        }
    }
}

结果:


这篇关于按名称在任何深度查询元素的 XDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆