CSharp - LINQ XML Ancestors

Introduction

The Ancestors operator returns a sequence containing the ancestor elements of each source node.

Prototypes

The Ancestors operator has two prototypes. The First Ancestors Prototype

public static IEnumerable<XElement> Ancestors<T> (
         this IEnumerable<T> source
       ) where T : XNode

This version of the operator can be called on a sequence of nodes, or objects derived from XNode.

It returns a sequence of elements containing the ancestor elements of each node in the source sequence.

The Second Ancestors Prototype

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

This version accepts a name, and only those ancestor elements matching the specified name are returned in the output sequence.

In the following example, first we create an XML document.

Next, we generate a sequence of FirstName elements.

Ancestors method is called on a sequence of nodes, not on a single node.

Demo

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

class Program// www. j a v  a  2 s  .  co  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.Ancestors())
        {
          Console.WriteLine("Ancestor element: {0}", element.Name);
        }
    }
}

Result

Related Topics