AncestorsAndSelf Method
Collapse the table of content
Expand the table of content

XElement.AncestorsAndSelf Method ()

 

Returns a collection of elements that contain this element, and the ancestors of this element.

Namespace:   System.Xml.Linq
Assembly:  System.Xml.Linq (in System.Xml.Linq.dll)

public IEnumerable<XElement> AncestorsAndSelf()

Return Value

Type: System.Collections.Generic.IEnumerable<XElement>

An IEnumerable<T> of XElement of elements that contain this element, and the ancestors of this element.

The elements in the returned collection are in reverse document order.

This method uses deferred execution.

The following example creates an XML tree. It then finds the GrandChild element, and then prints the ancestors of it.


                XElement xmlTree = new XElement("Root",
    new XElement("Child",
        new XElement("GrandChild", "element content")
    )
);
XElement gc = xmlTree.Element("Child").Element("GrandChild");
IEnumerable<XElement> aas =
    from el in gc.AncestorsAndSelf()
    select el;
foreach (XElement el in aas)
    Console.WriteLine(el.Name);

This example produces the following output:


                GrandChild
Child
Root

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 3.5
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show:
© 2016 Microsoft