我有一个XDocument
对象。我想使用LINQ在任何深度查询具有特定名称的元素。
当我使用Descendants("element_name")
时,我只获取当前级别的直接子元素。我正在寻找"//element_name“在XPath...should中的等价物我只使用XPath
,或者有没有办法使用LINQ方法来实现?
发布于 2009-06-23 15:07:20
下面是一个表示命名空间的示例:
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 );
}
发布于 2013-01-21 20:14:52
你可以这样做:
xml.Descendants().Where(p => p.Name.LocalName == "Name of the node to find")
其中xml
是一个XDocument
。
请注意,属性Name
返回一个具有LocalName
和Namespace
的对象。这就是为什么如果要按名称进行比较,就必须使用Name.LocalName
。
发布于 2009-02-19 16:52:40
子代将执行您所需的操作,但请确保已将名称空间名称与元素名称一起包含在内。如果你省略它,你可能会得到一个空的列表。
https://stackoverflow.com/questions/566167
复制相似问题