CSharp - LINQ XML AncestorsAndSelf

Introduction

The AncestorsAndSelf operator can be called on a sequence of elements.

It returns a sequence containing the ancestor elements of each source element and the source element itself.

This operator can be called only on elements, as opposed to on nodes.

It includes each source element in the returned sequence of ancestor elements.

Prototypes

The AncestorsAndSelf operator has two prototypes. The First AncestorsAndSelf Prototype

public static IEnumerable<XElement> AncestorsAndSelf (
  this IEnumerable<XElement> source
)

This version of the operator can be called on a sequence of elements and returns a sequence of elements containing each source element itself and its ancestor elements.

The Second AncestorsAndSelf Prototype

public static IEnumerable<XElement> AncestorsAndSelf<T> (
  this IEnumerable<XElement> source,
  XName name
)

This version accepts a name and only those source elements and its ancestors matching the specified name are returned.

The following code first creates an XML document.

Next, we generate a sequence of FirstName elements.

We then enumerate through the sequence displaying the source elements just so we can see the source sequence.

Then, we enumerate on the elements returned from the AncestorsAndSelf method and display them.

Demo

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

class Program//from w  w  w  .j  a  v a 2  s .c  o m
{
    static void Main(string[] args){
        XDocument xDocument = new XDocument(
          new XElement("Books",
            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"))));
        
              IEnumerable<XElement> elements =
                xDocument.Element("Books").Descendants("FirstName");
        
              //  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 the ancestor elements for each source element.
              foreach (XElement element in elements.AncestorsAndSelf())
              {
                Console.WriteLine("Ancestor element: {0}", element.Name);
              }

    }
}

Result

Related Topics