Share via


How to: Retrieve a Single Child Element (LINQ to XML)

This topic explains how to retrieve a single child element, given the name of the child element. When you know the name of the child element and that there is only one element that has this name, it can be convenient to retrieve just one element, instead of a collection.

The Element method returns the first child XElement with the specified XName.

If you want to retrieve a single child element in Visual Basic, a common approach is to use the XML property, and then retrieve the first element using array indexer notation.

Example

The following example demonstrates the use of the Element method. This example takes the XML tree named po and finds the first element named Comment.

The Visual Basic example shows using array indexer notation to retrieve a single element.

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

XElement po = XElement.Load("PurchaseOrder.xml");
XElement e = po.Element("DeliveryNotes");
Console.WriteLine(e);
Dim po As XElement = XElement.Load("PurchaseOrder.xml")
Dim e As XElement = po.<DeliveryNotes>(0)
Console.WriteLine(e)

This example produces the following output:

<DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>

The following example shows the same code 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.

XElement po = XElement.Load("PurchaseOrderInNamespace.xml");
XNamespace aw = "https://www.adventure-works.com";
XElement e = po.Element(aw + "DeliveryNotes");
Console.WriteLine(e);
Imports <xmlns:aw="https://www.adventure-works.com">

Module Module1
    Sub Main()
        Dim po As XElement = XElement.Load("PurchaseOrderInNamespace.xml")
        Dim e As XElement = po.<aw:DeliveryNotes>(0)
        Console.WriteLine(e)
    End Sub
End Module

This example produces the following output:

<aw:DeliveryNotes xmlns:aw="https://www.adventure-works.com">Please leave packages in shed by driveway.</aw:DeliveryNotes>

See Also

Concepts

LINQ to XML Axes