Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodes() vs DescendantNodes() usages?

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

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

however - I cant find any situation in which i will need the recursive way...

When should I prefer working with DescendantNodes() over Nodes() ?

i.e :

enter image description here

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

output :

enter image description here question :

Why will i need it recursively splitted ,when I can work with Nodes() ?

like image 306
Royi Namir Avatar asked Feb 22 '23 01:02

Royi Namir


1 Answers

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.

like image 122
Martin Honnen Avatar answered Mar 07 '23 15:03

Martin Honnen