XDocument.Descendants()与DescendantNodes()

Rob*_* P. 23 c# xml linq-to-xml

我看过Nodes()vs DescendantNodes()用法?看看和之间的区别.Nodes(),.DescendantNodes()但有什么区别:

XDocument.Descendants()和XDocument.DescendantNodes()?

var xmlDoc = XDocument.Load(@"c:\Projects\Fun\LINQ\LINQ\App.config");        
var descendants = xmlDoc.Descendants();
var descendantNodes = xmlDoc.DescendantNodes();

foreach (var d in descendants)
    Console.WriteLine(d);

foreach (var d in descendantNodes)
    Console.WriteLine(d);
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 30

后代只返回元素.DescendantNodes返回所有节点(包括XComments,XText,XDocumentType等).

考虑使用xml来查看差异:

<root>
  <!-- comment -->
  <foo>
    <bar value="42"/>Oops!
  </foo>  
</root>
Run Code Online (Sandbox Code Playgroud)

Descendants将返回3个元素(root,foo,bar).DescendantNodes将返回这三个元素,以及其他2个节点 - 文本和注释.


Tho*_*que 14

Descendants只返回后代元素,同时DescendantNodes返回所有类型的节点(元素,属性,文本节点,注释等)

所以Descendants()相当于DescendantNodes().OfType<XElement>().