共用方式為


XNode.Ancestors Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Returns a collection of the ancestor elements of this node.

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

Syntax

'Declaration
Public Function Ancestors As IEnumerable(Of XElement)
public IEnumerable<XElement> Ancestors()

Return Value

Type: System.Collections.Generic.IEnumerable<XElement>
An IEnumerable<T> of XElement of the ancestor elements of this node.

Remarks

This method does not return itself in the results.

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

This method uses deferred execution.

Examples

The following example uses this method to enumerate the ancestors of a node.

Dim output As New StringBuilder
Dim xmlTree As XElement = _
        <Root>
            <Child>
                <GrandChild>content</GrandChild>
            </Child>
        </Root>

Dim grandChild As IEnumerable(Of XElement) = xmlTree...<GrandChild>
For Each el In grandChild.Ancestors()
    output.Append(el.Name)
    output.Append(Environment.NewLine)
Next

OutputTextBlock.Text = output.ToString()
StringBuilder output = new StringBuilder();
XElement xmlTree = new XElement("Root",
    new XElement("Child",
        new XElement("GrandChild", "content")
    )
);
IEnumerable<XElement> grandChild = xmlTree.Descendants("GrandChild");
foreach (XElement el in grandChild.Ancestors())
    output.Append(el.Name + Environment.NewLine);

OutputTextBlock.Text = output.ToString();

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.