Export (0) Print
Expand All

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.

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);

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 = "http://www.adventure-works.com";
XElement e = po.Element(aw + "DeliveryNotes");
Console.WriteLine(e);

This example produces the following output:

<aw:DeliveryNotes xmlns:aw="http://www.adventure-works.com">Please leave packages in shed by driveway.</aw:DeliveryNotes>
Show:
© 2014 Microsoft