CSharp - LINQ XML Elements

Introduction

Elements operator operates on a sequence of elements or documents and returns a sequence of elements containing each source element's or document's child elements.

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

Descendants operator recursively returns all child elements until the end of each tree is reached.

Prototypes

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

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

The Second Element s Prototype

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

This version returns elements by the specified name.

Demo

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

class Program/* ww  w .j  a v  a 2 s  . c  om*/
{
    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 elements.
        foreach (XElement element in elements.Elements())
        {
          Console.WriteLine("Child element: {0}", element);
        }
    }
}

Result

Related Topics