CSharp - LINQ XML Nodes

Introduction

The Nodes operator can be called on a sequence of elements or documents.

It returns a sequence of nodes containing each source element's or document's child nodes.

Nodes operator returns only the immediate child elements of each element in the source sequence of elements.

DescendantNodes operator recursively returns all child nodes until the end of each tree is reached.

Prototypes

public static IEnumerable<XNode> Nodes<T> (
        this IEnumerable<T> source
      ) where T : XContainer

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program//from   www . j  a  va2s  .  co  m
{
    static void Main(string[] args){
        XDocument xDocument = new XDocument(
          new XElement("Books",
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XComment("This is a new author."),
              new XElement("FirstName", "Joe"),
              new XElement("LastName", "Ruby")),
            new XElement("Book",
              new XAttribute("type", "Editor"),
              new XElement("FirstName", "PHP"),
              new XElement("LastName", "Python"))));
        
        IEnumerable<XElement> elements =
          xDocument.Element("Books").Elements("Book");
        
        //  First, we will display the source elements.
        foreach (XElement element in elements)
        {
          Console.WriteLine("Source element: {0} : value = {1}",
            element.Name, element.Value);
        }
        
        //  Now, we will display each source element's child nodes.
        foreach (XNode node in elements.Nodes())
        {
          Console.WriteLine("Child node: {0}", node);
        }
    }
}

Result