Nodes() vs DescendantNodes() usages?

后端 未结 1 1749
独厮守ぢ
独厮守ぢ 2021-01-14 03:43

I read that Nodes() emits all the nodes including sub.

and DescendantNodes() the same but in a recursive way.

however - I cant fin

相关标签:
1条回答
  • 2021-01-14 04:28

    Well nodes gives you the child nodes of the node you call it on while descendantnodes gives you the descendant nodes of the node you call it on.

    Imagine you have an XML document you want to process with several levels of nesting and you want to find all comment nodes at all levels, then you can do

    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);
        }
    

    If you solely used the Nodes method you would need to write a recursive method to find all comment nodes.

    0 讨论(0)
提交回复
热议问题