Roy*_*mir 3 .net-4.0 linq-to-xml c#-4.0
我读到Nodes()发出包括sub在内的所有节点.
和 DescendantNodes()相同但以递归方式.
但是 - 我无法找到任何需要递归方式的情况......
我应该何时更喜欢使用DescendantNodes()over Nodes()?
即:

IEnumerable<XNode> nodes =from nd in xmlTree.DescendantNodes()
select nd;
foreach (XNode node in nodes)
Console.WriteLine(node);
Run Code Online (Sandbox Code Playgroud)
输出:
题 :
当我可以使用Nodes()时,为什么我需要递归拆分呢?
Well 节点为您提供您调用它的节点的子节点,而descendantnodes为您提供调用它的节点的后代节点.
想象一下,你有一个XML文档想要处理几个嵌套级别,你想要找到所有级别的所有注释节点,那么你可以做
XDocument doc = XDocument.Parse(@"<!-- comment 1 -->
<root>
<!-- comment 2 -->
<foo>
<!-- comment 3 -->
<bar><!-- comment 4 --></bar>
</foo>
</root>
<!-- comment 5 -->");
foreach (XComment comment in doc.DescendantNodes().OfType<XComment>())
{
Console.WriteLine(comment.Value);
}
Run Code Online (Sandbox Code Playgroud)
如果您只使用该Nodes方法,则需要编写递归方法来查找所有注释节点.