Export (0) Print
Expand All

How to: Find Descendant Elements (XPath-LINQ to XML)

This topic shows how to get the descendant elements with a particular name.

The XPath expression is //Name.

This example finds all descendants named Name.

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

XDocument po = XDocument.Load("PurchaseOrders.xml");

// LINQ to XML query
IEnumerable<XElement> list1 = po.Root.Descendants("Name");

// XPath expression
IEnumerable<XElement> list2 = po.XPathSelectElements("//Name");

if (list1.Count() == list2.Count() &&
        list1.Intersect(list2).Count() == list1.Count())
    Console.WriteLine("Results are identical");
else
    Console.WriteLine("Results differ");
foreach (XElement el in list1)
    Console.WriteLine(el);

This example produces the following output:

Results are identical
<Name>Ellen Adams</Name>
<Name>Tai Yee</Name>
<Name>Cristian Osorio</Name>
<Name>Cristian Osorio</Name>
<Name>Jessica Arnold</Name>
<Name>Jessica Arnold</Name>
Show:
© 2014 Microsoft