CSharp - Traversing Down from an XElement Object via the Nodes Method

Introduction

Nodes() method is returning all child nodes, not just elements.

This could include comments (XComment), text (XText), processing instructions (XProcessingInstruction), document type (XDocumentType), or elements (XElement).

It does not include the attribute because an attribute is not a node.

Demo

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

class Program//  w ww.j  a va 2  s.c  o m
{
    static void Main(string[] args){
          XElement firstParticipant;
    
          //  A full document with all the bells and whistles.
          XDocument xDocument = new XDocument(
            new XDeclaration("1.0", "UTF-8", "yes"),
            new XDocumentType("Books", null, "Books.dtd", null),
            new XProcessingInstruction("BookCataloger", "out-of-print"),
            //  Notice on the next line that we are saving off a reference to the first
            //  Book element.
            new XElement("Books", firstParticipant =
              new XElement("Book",
                new XAttribute("type", "Author"),
                new XElement("FirstName", "Joe"),
                new XElement("LastName", "Ruby")),
              new XElement("Book",
                new XAttribute("type", "Editor"),
                new XElement("FirstName", "PHP"),
                new XElement("LastName", "Python"))));
    
          foreach (XNode node in firstParticipant.Nodes())
          {
            Console.WriteLine(node);
          }
    }
}

Result

Related Topic