xdocument descendantsnodes vs nodes

时间:2014-03-17 14:12:23

标签: c# linq c#-4.0 linq-to-xml

我试图理解扩展方法,DescendantsnNodes和方法,XDocument类的“节点”之间的区别。

我可以看到DescendantsNodes应该返回此文档或元素的所有后代 和节点应返回此文档或元素的所有子节点。

我不明白“所有子节点”和“所有后代”之间的区别是什么。

有人可以澄清这个吗?

2 个答案:

答案 0 :(得分:0)

鉴于

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

root元素节点有一个子节点,一个child元素节点,但有三个后代节点,即child元素节点,grandchild元素节点和foo文字节点。

答案 1 :(得分:0)

子节点将是直接在某个节点(父节点)下面的节点。后代将是在同一节点“下面”的节点,但它也可以是子节点“下面”的多个级别。

子节点将是后代,但后代并不总是子节点。

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

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

使用小代码示例进行可视化可能更容易:

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

产地:

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>