CSharp - Get element by name using AncestorsAndSelf operator

Description

Get element by name using AncestorsAndSelf operator

Demo

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

class Program/*from   www . j ava 2s . 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("Book"))
        {
          Console.WriteLine("Ancestor element: {0}", element.Name);
        }
    }
}

Result

Related Topic