XContainer.DescendantNodes Method

Definition

Returns a collection of the descendant nodes for this document or element, in document order.

C#
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes();

Returns

An IEnumerable<T> of XNode containing the descendant nodes of the XContainer, in document order.

Examples

The following example creates an XML tree, and then iterates through the DescendantNodes axis.

C#
XElement xmlTree = new XElement("Root",  
    // Attributes are not nodes, so will not be returned by DescendantNodes.  
    new XAttribute("Att1", "AttributeContent"),  
    new XElement("Child",  
        new XElement("GrandChild", "element content")  
    )  
);  
IEnumerable<XNode> dnas =  
    from node in xmlTree.DescendantNodes()  
    select node;  
foreach (XNode node in dnas)  
{  
    if (node is XElement)  
        Console.WriteLine((node as XElement).Name);  
    else  
        Console.WriteLine(node);  
}  

This example produces the following output:

Child  
GrandChild  
element content  

Remarks

Note that attributes are not considered to be nodes in LINQ to XML, so they will not be part of the collection that is returned by this method.

This method uses deferred execution.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also