CSharp - LINQ XML Descendants

Introduction

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

It returns a sequence of elements containing each source element's or document's descendant elements.

Prototypes

The Descendants operator has two prototypes. The First Descendants Prototype:

public static IEnumerable<XElement> Descendants<T> (
        this IEnumerable<T> source
      ) where T : XContainer

This method is called on a sequence of elements or documents, as opposed to a single element or document.

The Second Descendants Prototype

public static IEnumerable<XElement> Descendants<T> (
        this IEnumerable<T> source,
        XName name
      ) where T : XContainer

This version returns elements by the specified name in the output sequence.

Demo

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

class Program/*from w  ww  .  j ava  2s.  com*/
{
    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 descendant elements.
            foreach (XElement element in elements.Descendants())
            {
              Console.WriteLine("Descendant element: {0}", element);
            }
    }
}

Result

Related Topics