2012-03-24 84 views
3

我读过Nodes()发出的所有节点,包括子。节点()vs DescendantNodes()用法?

DescendantNodes()相同,但以递归方式。

但是 - 我不能找到任何情况中,我将需要递归的方式...

我应该什么时候喜欢用DescendantNodes()在Nodes()工作?

即:

enter image description here

IEnumerable<XNode> nodes =from nd in xmlTree.DescendantNodes() 
       select nd; 
      foreach (XNode node in nodes) 
       Console.WriteLine(node); 

输出:

enter image description here 问题:

为什么我需要它递归分裂,当我可以与节点工作()?

回答

7

nodes给你你调用它的节点的子节点,而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); 
    } 

如果你只使用了Nodes方法你将需要编写一个递归方法来查找所有评论节点。