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

查看:138
本文介绍了按名称在任何深度查询一个XDocument的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的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" />

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

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