Select XML Nodes by Name or Attribute Value in C#

To pull specific elements out of an XML document you can either write an XPath query against an XmlDocument or filter an XDocument with LINQ to XML. Both are built into .NET. XPath is compact and familiar if you already know it; LINQ to XML is easier to read and safer when the filter value comes from user input.

All examples use this document:

const string xml = """
    <Names>
      <Name type="M">
        <FirstName>Lionel</FirstName>
        <LastName>Messi</LastName>
      </Name>
      <Name type="M">
        <FirstName>Cristiano</FirstName>
        <LastName>Ronaldo</LastName>
      </Name>
      <Name type="F">
        <FirstName>Maria</FirstName>
        <LastName>Sharapova</LastName>
      </Name>
    </Names>
    """;

XmlDocument and XPath

SelectNodes returns every node that matches an XPath expression. SelectSingleNode returns the first match, or null if there is none.

using System.Xml;

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

// All <Name> elements directly under the root <Names> element
foreach (XmlNode name in doc.SelectNodes("/Names/Name")!)
{
    Console.WriteLine($"{name["FirstName"]?.InnerText} {name["LastName"]?.InnerText}");
}
// Lionel Messi
// Cristiano Ronaldo
// Maria Sharapova

The leading / anchors the path at the document root, so /Names/Name only matches <Name> elements that are children of a root element called <Names>. Indexing a node by tag name, as in name["FirstName"], returns the first child element with that name, or null. The ?. keeps a missing element from throwing.

Filter by attribute value

Put the condition in square brackets and prefix the attribute name with @:

foreach (XmlNode name in doc.SelectNodes("/Names/Name[@type='M']")!)
{
    Console.WriteLine(name["FirstName"]?.InnerText);
}
// Lionel
// Cristiano

XmlNode? first = doc.SelectSingleNode("/Names/Name[@type='F']");
Console.WriteLine(first?["LastName"]?.InnerText);
// Sharapova

To read an attribute rather than filter on it, cast to XmlElement and call GetAttribute, which returns an empty string when the attribute is missing:

if (doc.SelectSingleNode("/Names/Name") is XmlElement element)
{
    Console.WriteLine(element.GetAttribute("type")); // M
}

A few other expressions that come up often:

XPathSelects
//FirstNameEvery <FirstName> element, at any depth
/Names/Name[@type]<Name> elements that have a type attribute at all
/Names/Name[FirstName='Maria']<Name> elements whose <FirstName> child equals “Maria”
//Name/@typeThe type attribute nodes themselves

// searches the whole document. On large files it is noticeably slower than a full path, so spell out the path when you know it.

LINQ to XML

The same queries with XDocument:

using System.Xml.Linq;

XDocument doc = XDocument.Parse(xml);

var men = doc.Root!
    .Elements("Name")
    .Where(n => (string?)n.Attribute("type") == "M");

foreach (XElement name in men)
{
    Console.WriteLine($"{(string?)name.Element("FirstName")} {(string?)name.Element("LastName")}");
}
// Lionel Messi
// Cristiano Ronaldo

Elements looks at direct children only; Descendants("FirstName") is the equivalent of //FirstName. Casting an XAttribute or XElement to string? returns null when the node is missing, which is why the code uses casts instead of .Value (that would throw a NullReferenceException).

Which one to use

For new code, LINQ to XML. The filter is ordinary C#, so you get compile-time checking, and you never have to build a query string. That matters as soon as the value comes from a variable: $"/Names/Name[LastName='{lastName}']" breaks on a name like O’Neill and lets a crafted input change the meaning of the query (XPath injection). With LINQ, n => (string?)n.Element("LastName") == lastName is safe for any value.

Stay with XmlDocument and XPath when you are maintaining code that already uses it, when the XPath expressions live in configuration, or when an API hands you an XmlNode. You can also run XPath on an XDocument through the XPathSelectElements extension method in System.Xml.XPath.

One trap catches everyone once: if the root element declares a default namespace (<Names xmlns="urn:example">), /Names/Name matches nothing. XPath needs an XmlNamespaceManager with a prefix, and LINQ to XML needs an XNamespace, as in doc.Root!.Elements(ns + "Name"). The XPath post linked below shows the namespace manager in full.

Related examples

Leave a Comment