Search code examples
c#-4.0.net-4.0linq-to-xml

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() ?


Solution

    • Nodes gives you the direct child nodes of the node you call it on.
    • DescendantNodes gives you all descendant nodes (children, grandchildren, etc) 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.