How to: Filter on Element Names (LINQ to XML)

When you call one of the methods that return IEnumerable<T> of XElement, you can filter on the element name.

Example

This example retrieves a collection of descendants that is filtered to contain only descendants with the specified name.

This example uses the following XML document: Sample XML File: Typical Purchase Order (LINQ to XML).

XElement po = XElement.Load("PurchaseOrder.xml");
IEnumerable<XElement> items =
    from el in po.Descendants("ProductName")
    select el;
foreach(XElement prdName in items)
    Console.WriteLine(prdName.Name + ":" + (string) prdName);
Dim po As XElement = XElement.Load("PurchaseOrder.xml")
Dim items As IEnumerable(Of XElement) = _
    From el In po...<ProductName> _
    Select el
For Each prdName As XElement In items
    Console.WriteLine(prdName.Name.ToString & ":" & prdName.Value)
Next

This code produces the following output:

ProductName:Lawnmower
ProductName:Baby Monitor

The other methods that return IEnumerable<T> of XElement collections follow the same pattern. Their signatures are similar to Elements and Descendants. The following is the complete list of methods that have similar method signatures:

The following example shows the same query for XML that is in a namespace. For more information, see Working with XML Namespaces.

This example uses the following XML document: Sample XML File: Typical Purchase Order in a Namespace.

XNamespace aw = "https://www.adventure-works.com";
XElement po = XElement.Load("PurchaseOrderInNamespace.xml");
IEnumerable<XElement> items =
    from el in po.Descendants(aw + "ProductName")
    select el;
foreach (XElement prdName in items)
    Console.WriteLine(prdName.Name + ":" + (string)prdName);
Imports <xmlns:aw="https://www.adventure-works.com">

Module Module1
    Sub Main()
        Dim po As XElement = XElement.Load("PurchaseOrderInNamespace.xml")
        Dim items As IEnumerable(Of XElement) = _
            From el In po...<aw:ProductName> _
            Select el
        For Each prdName As XElement In items
            Console.WriteLine(prdName.Name.ToString & ":" & prdName.Value)
        Next
    End Sub
End Module

This code produces the following output:

{https://www.adventure-works.com}ProductName:Lawnmower
{https://www.adventure-works.com}ProductName:Baby Monitor

See Also

Concepts

LINQ to XML Axes