What is the difference XElement Nodes() vs Elements()?

osexpert picture osexpert · Jun 10, 2016 · Viewed 8.9k times · Source

Documentation says:


XContainer.Nodes Method () Returns a collection of the child nodes of this element or document, in document order.

Remarks Note that the content does not include attributes. In LINQ to XML, attributes are not considered to be nodes of the tree. They are name/value pairs associated with an element.

XContainer.Elements Method () Returns a collection of the child elements of this element or document, in document order.


So it looks like Nodes() has a limitation, but then why does it exist? Are there any possible reasons or advantages of using Nodes()?

Answer

Evk picture Evk · Jun 10, 2016

The reason is simple: XNode is a base (abstract) class for all xml "parts", and XElement is just one such part (so XElement is subclass of XNode). Consider this code:

XDocument doc = XDocument.Parse("<root><el1 />some text<!-- comment --></root>");
foreach (var node in doc.Root.Nodes()) {
      Console.WriteLine(node);
}
foreach (var element in doc.Root.Elements()) {
      Console.WriteLine(element);
}

Second loop (over Elements()) will only return one item: <el />

First loop however will return also text node (some text) and comment node (<!-- comment -->), so you see the difference.

You can see what other descendants of XNode there are in documentaiton of XNode class.