How to query LINQ to XML using XPath (LINQ to XML)

This article introduces the extension methods that enable you to query an XML tree by using XPath. For detailed information about using these extension methods, see System.Xml.XPath.Extensions.


Unless you have a very specific reason for querying using XPath, such as extensive use of legacy code, using XPath with LINQ to XML isn't recommended. XPath queries won't perform as well as LINQ to XML queries.


The following example creates a small XML tree and uses XPathSelectElements to select a set of elements.

XElement root = new XElement("Root",
    new XElement("Child1", 1),
    new XElement("Child1", 2),
    new XElement("Child1", 3),
    new XElement("Child2", 4),
    new XElement("Child2", 5),
    new XElement("Child2", 6)
IEnumerable<XElement> list = root.XPathSelectElements("./Child2");
foreach (XElement el in list)
Dim root As XElement = _

Dim list As IEnumerable(Of XElement) = root.XPathSelectElements("./Child2")
For Each el As XElement In list

This example produces the following output: