xdocument descendantsnodes vs nodes

好久不见. 提交于 2021-01-29 18:14:18

问题


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?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/22456615/xdocument-descendantsnodes-vs-nodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!