Select XML Nodes with XPath in C#: Filters, Functions, Namespaces

XPath lets you describe which nodes you want with a short path expression instead of looping over the tree yourself. In .NET you run XPath with SelectNodes and SelectSingleNode on an XmlDocument, or with the XPathSelectElements extension methods on an XDocument. Both live in the base library; no package is needed.

The examples use this document:

using System.Xml;

const string xml = """
    <Vegetables>
      <Vegetable><Name>Pepper</Name><Price>10</Price></Vegetable>
      <Vegetable><Name>Onion</Name><Price>20</Price></Vegetable>
      <Vegetable><Name>Garlic</Name><Price>5</Price></Vegetable>
      <Vegetable><Name>Corn</Name><Price>35</Price></Vegetable>
    </Vegetables>
    """;

var doc = new XmlDocument();
doc.LoadXml(xml);

Filter by position

foreach (XmlNode node in doc.SelectNodes("/Vegetables/Vegetable[position() <= 2]")!)
{
    Console.WriteLine($"Vegetable: {node["Name"]?.InnerText}");
}
// Vegetable: Pepper
// Vegetable: Onion

XmlNode? last = doc.SelectSingleNode("/Vegetables/Vegetable[last()]");
Console.WriteLine(last?["Name"]?.InnerText);
// Corn

XPath positions start at 1, not 0. [1] is shorthand for [position() = 1].

Filter by a child’s value

A predicate can compare a child element’s text. Add a path after the predicate to select something other than the matching element itself:

foreach (XmlNode node in doc.SelectNodes("/Vegetables/Vegetable[Price > 15]/Price")!)
{
    Console.WriteLine($"Price: {node.InnerText}");
}
// Price: 20
// Price: 35

foreach (XmlNode node in doc.SelectNodes("/Vegetables/Vegetable[starts-with(Name, 'C')]/Name")!)
{
    Console.WriteLine(node.InnerText);
}
// Corn

Price > 15 converts the text of <Price> to a number before comparing. If the text is not a valid XPath number, for example 15,50 with a comma or 15 EUR, it becomes NaN and the comparison is quietly false. XPath numbers always use a period as the decimal separator, whatever the current culture.

Calculate values

Expressions that return a number, a string or a boolean go through XPathNavigator.Evaluate instead of SelectNodes:

var navigator = doc.CreateNavigator()!;

Console.WriteLine(navigator.Evaluate("count(/Vegetables/Vegetable)"));     // 4
Console.WriteLine(navigator.Evaluate("sum(/Vegetables/Vegetable/Price)")); // 70

Evaluate returns object. For count and sum the value is a double, so cast it with (double) before doing arithmetic.

.NET implements XPath 1.0 only. Functions from XPath 2.0 and later, such as lower-case, ends-with or matches, throw an XPathException. For anything beyond XPath 1.0, select the nodes and finish the job in C#.

XPath on XDocument

If the rest of your code uses LINQ to XML, you do not have to switch to XmlDocument. The System.Xml.XPath namespace adds extension methods to XNode:

using System.Xml.Linq;
using System.Xml.XPath;

XDocument xdoc = XDocument.Parse(xml);

foreach (XElement name in xdoc.XPathSelectElements("/Vegetables/Vegetable[Price > 15]/Name"))
{
    Console.WriteLine(name.Value);
}
// Onion
// Corn

XPathSelectElement returns the first match and XPathEvaluate corresponds to Evaluate above.

Documents with namespaces

Most real-world XML (RSS, SOAP, Office files, anything with a schema) declares a namespace on the root element. Then a plain path finds nothing:

var nsDoc = new XmlDocument();
nsDoc.LoadXml("""
    <Vegetables xmlns="urn:example:shop">
      <Vegetable><Name>Pepper</Name><Price>10</Price></Vegetable>
    </Vegetables>
    """);

Console.WriteLine(nsDoc.SelectNodes("/Vegetables/Vegetable")!.Count); // 0

XPath 1.0 has no notion of a default namespace, so you register the namespace under a prefix of your choice and use that prefix in the query:

var ns = new XmlNamespaceManager(nsDoc.NameTable);
ns.AddNamespace("s", "urn:example:shop");

XmlNodeList vegetables = nsDoc.SelectNodes("/s:Vegetables/s:Vegetable", ns)!;
Console.WriteLine(vegetables.Count); // 1

The prefix does not have to match anything in the document. Only the namespace URI has to be identical.

Building queries from input

Concatenating a variable into an expression, as in $"//Vegetable[Name='{searchName}']", fails when the value contains an apostrophe and lets a crafted value change the query. If the value comes from outside your code, either validate it strictly or filter with LINQ to XML, where the value is an ordinary C# string:

string searchName = Console.ReadLine() ?? "";

XElement? match = xdoc.Root!
    .Elements("Vegetable")
    .FirstOrDefault(v => (string?)v.Element("Name") == searchName);

Related examples

Leave a Comment