XDocument.Descendants() versus DescendantNodes()

亡梦爱人 提交于 2019-12-22 01:43:32

问题


I've looked at Nodes() vs DescendantNodes() usages? to see the difference between .Nodes() and .DescendantNodes() but what is the difference between:

XDocument.Descendants() and 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);

回答1:


Descendants returns only elements. DescendantNodes returns all nodes (including XComments, XText, XDocumentType etc).

Consider following xml to see the difference:

<root>
  <!-- comment -->
  <foo>
    <bar value="42"/>Oops!
  </foo>  
</root>

Descendants will return 3 elements (root, foo, bar). DescendantNodes will return these three elements, and 2 other nodes - text and comment.




回答2:


Descendants returns only descendant elements, while DescendantNodes returns all types of nodes (elements, attributes, text nodes, comments, etc)

So Descendants() is equivalent to DescendantNodes().OfType<XElement>().



来源:https://stackoverflow.com/questions/23849946/xdocument-descendants-versus-descendantnodes

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