Compartilhar via


How to: Find a Child Element (XPath-LINQ to XML)

This topic compares the XPath child element axis to the LINQ to XML Element method.

The XPath expression is DeliveryNotes.

Example

This example finds the child element DeliveryNotes.

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

XDocument cpo = XDocument.Load("PurchaseOrders.xml");
XElement po = cpo.Root.Element("PurchaseOrder");

// LINQ to XML query
XElement el1 = po.Element("DeliveryNotes");

// XPath expression
XElement el2 = po.XPathSelectElement("DeliveryNotes");
// same as "child::DeliveryNotes"
// same as "./DeliveryNotes"

if (el1 == el2)
    Console.WriteLine("Results are identical");
else
    Console.WriteLine("Results differ");
Console.WriteLine(el1);
Dim cpo As XDocument = XDocument.Load("PurchaseOrders.xml")
Dim po As XElement = cpo.Root.<PurchaseOrder>.FirstOrDefault

'LINQ to XML query
Dim el1 As XElement = po.<DeliveryNotes>.FirstOrDefault

' XPath expression
Dim el2 As XElement = po.XPathSelectElement("DeliveryNotes")
' same as "child::DeliveryNotes"
' same as "./DeliveryNotes"

If el1 Is el2 Then
    Console.WriteLine("Results are identical")
Else
    Console.WriteLine("Results differ")
End If
Console.WriteLine(el1)

This example produces the following output:

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

See Also

Concepts

LINQ to XML for XPath Users