首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >按任意深度按名称查询元素的XDocument

按任意深度按名称查询元素的XDocument
EN

Stack Overflow用户
提问于 2009-02-19 16:46:09
回答 5查看 275.1K关注 0票数 151

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

当我使用Descendants("element_name")时,我只获取当前级别的直接子元素。我正在寻找"//element_name“在XPath...should中的等价物我只使用XPath,或者有没有办法使用LINQ方法来实现?

EN

回答 5

Stack Overflow用户

发布于 2009-06-23 15:07:20

下面是一个表示命名空间的示例:

代码语言:javascript
复制
String TheDocumentContent =
@"
<TheNamespace:root xmlns:TheNamespace = 'http://www.w3.org/2001/XMLSchema' >
   <TheNamespace:GrandParent>
      <TheNamespace:Parent>
         <TheNamespace:Child theName = 'Fred'  />
         <TheNamespace:Child theName = 'Gabi'  />
         <TheNamespace:Child theName = 'George'/>
         <TheNamespace:Child theName = 'Grace' />
         <TheNamespace:Child theName = 'Sam'   />
      </TheNamespace:Parent>
   </TheNamespace:GrandParent>
</TheNamespace:root>
";

XDocument TheDocument = XDocument.Parse( TheDocumentContent );

//Example 1:
var TheElements1 =
from
    AnyElement
in
    TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
select
    AnyElement;

ResultsTxt.AppendText( TheElements1.Count().ToString() );

//Example 2:
var TheElements2 =
from
    AnyElement
in
    TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
where
    AnyElement.Attribute( "theName" ).Value.StartsWith( "G" )
select
    AnyElement;

foreach ( XElement CurrentElement in TheElements2 )
{
    ResultsTxt.AppendText( "\r\n" + CurrentElement.Attribute( "theName" ).Value );
}
票数 56
EN

Stack Overflow用户

发布于 2013-01-21 20:14:52

你可以这样做:

代码语言:javascript
复制
xml.Descendants().Where(p => p.Name.LocalName == "Name of the node to find")

其中xml是一个XDocument

请注意,属性Name返回一个具有LocalNameNamespace的对象。这就是为什么如果要按名称进行比较,就必须使用Name.LocalName

票数 46
EN

Stack Overflow用户

发布于 2009-02-19 16:52:40

子代将执行您所需的操作,但请确保已将名称空间名称与元素名称一起包含在内。如果你省略它,你可能会得到一个空的列表。

票数 22
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/566167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档