xdocument descendantsnodes vs nodes

280 views Asked by At

I'm trying to understand the difference between the extension method, DescendantsnNodes and the method, "Nodes" of the class XDocument.

I can see that the DescendantsNodes should return all descendants of this document or element and Nodes should return all child nodes of this document or element.

I don't understand what's the difference between "all child nodes" and "all descendants".

could someone please clarify this?

2

There are 2 answers

0
Chris On BEST ANSWER

A child node would be a node which is directly "underneath" a certain node (parent). A descendant would be a node which is "underneath" the same node, but it could also be a number of levels "underneath" the child node.

A child node will be a descendant, but a descendant won't always be a child node.

Eg: <Parent><Child1 /><Child2><AnotherNode /></Child2></Parent>

-Parent
   |
    --> Child1 (Descendant)
   |   
    --> Child2 (Descendant)
          |
           --> AnotherNode (Descendant, not child)    

It might be easier to visualise with a small code sample:

string someXML = "<Root><Child1>Test</Child1><Child2><GrandChild></GrandChild></Child2></Root>";

var xml = XDocument.Parse(someXML);

Console.WriteLine ("XML:");
Console.WriteLine (xml);

Console.WriteLine ("\nNodes();\n");

foreach (XNode node in xml.Descendants("Root").Nodes())
{
    Console.WriteLine ("Child Node:");
    Console.WriteLine (node);
    Console.WriteLine ("");
}

Console.WriteLine ("DescendantNodes();\n");

foreach (XNode node in xml.Descendants("Root").DescendantNodes())
{
    Console.WriteLine ("Descendent Node:");
    Console.WriteLine (node);
    Console.WriteLine ("");
}

Produces:

XML:

<Root>
  <Child1>Test</Child1>
  <Child2>
    <GrandChild></GrandChild>
  </Child2>
</Root>

Nodes();

Child Node:    
<Child1>Test</Child1>

Child Node:    
<Child2>
  <GrandChild></GrandChild>
</Child2>

DescendantNodes();

Descendent Node:    
<Child1>Test</Child1>

Descendent Node:    
Test

Descendent Node:    
<Child2>
  <GrandChild></GrandChild>
</Child2>

Descendent Node:
<GrandChild></GrandChild>
0
Martin Honnen On

Given

<root><child><grandchild>foo</grandchild></child></root>

the root element node has one child node, a child element node, but three descendant nodes, namely the child element node, the grandchild element node and the foo text node.