【问题标题】:Nodes() vs DescendantNodes() usages?Nodes() vs DescendantNodes() 用法?
【发布时间】:2014-10-19 12:44:48
【问题描述】:

我读到Nodes() 发出所有节点,包括 sub。

和DescendantNodes() 相同,但采用递归方式。

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

我应该在什么时候更喜欢使用DescendantNodes() 而不是Nodes()?

即:

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

输出:

问题:

当我可以使用 Nodes() 时,为什么我需要递归拆分它?

【问题讨论】:

    标签: c#-4.0 .net-4.0 linq-to-xml


    【解决方案1】:

    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 方法,则需要编写一个递归方法来查找所有评论节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2014-12-23
      • 2013-03-17
      • 2017-08-25
      • 2020-11-17
      相关资源
      最近更新 更多