Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument.Descendants() versus DescendantNodes()

Tags:

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); 
like image 584
Rob P. Avatar asked May 24 '14 21:05

Rob P.


2 Answers

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.

like image 68
Sergey Berezovskiy Avatar answered Sep 29 '22 06:09

Sergey Berezovskiy


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>().

like image 21
Thomas Levesque Avatar answered Sep 29 '22 07:09

Thomas Levesque