XPath
XDocument
XML
XML Parsing
C#

how to use XPath with XDocument?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

XDocument belongs to LINQ to XML, which means its most natural query style is LINQ. Even so, you can still use XPath against an XDocument in .NET by importing the XPath extension methods from System.Xml.XPath.

The Required Namespace

The most common mistake is loading an XDocument correctly but forgetting the namespace that adds XPath extension methods.

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

Once System.Xml.XPath is imported, you can call methods such as XPathSelectElement, XPathSelectElements, and XPathEvaluate.

Basic Example

Here is a simple query that finds all book titles from an XML document:

csharp
1using System;
2using System.Linq;
3using System.Xml.Linq;
4using System.Xml.XPath;
5
6class Program
7{
8    static void Main()
9    {
10        string xml = @"
11            <bookstore>
12              <book category='fiction'>
13                <title>Foundation</title>
14              </book>
15              <book category='science'>
16                <title>A Brief History of Time</title>
17              </book>
18            </bookstore>";
19
20        XDocument doc = XDocument.Parse(xml);
21
22        var titles = doc.XPathSelectElements("//book/title");
23
24        foreach (XElement title in titles)
25        {
26            Console.WriteLine(title.Value);
27        }
28    }
29}

This is useful when you already know the XPath expression you want and do not want to rewrite it as LINQ.

Selecting a Single Element

If you expect exactly one match, XPathSelectElement is simpler:

csharp
XElement? firstScienceBook = doc.XPathSelectElement("//book[@category='science']");
Console.WriteLine(firstScienceBook?.Element("title")?.Value);

The XPath predicate filters on the category attribute. This is one of the big reasons people still reach for XPath: compact filtering syntax.

Working with XML Namespaces

Namespace-aware XML requires extra setup. A plain XPath query usually fails if the XML uses namespaces and you ignore them.

csharp
1using System.Xml;
2
3XDocument doc = XDocument.Parse(@"
4<root xmlns='urn:demo'>
5  <item id='1'>one</item>
6</root>");
7
8var manager = new XmlNamespaceManager(new NameTable());
9manager.AddNamespace("d", "urn:demo");
10
11var item = doc.XPathSelectElement("//d:item[@id='1']", manager);
12Console.WriteLine(item?.Value);

Without the namespace manager, the query returns no match even though the element obviously exists.

XPath vs LINQ to XML

XPath is great when:

  • you already have existing XPath expressions
  • the query is easier to read in XPath form
  • you need compact attribute-based filtering

LINQ to XML is often better when:

  • you want strong C# typing and composability
  • the query logic is built dynamically in code
  • you prefer native LINQ transformations over string expressions

Both are valid. The main thing is to choose one style intentionally instead of mixing them randomly.

If you inherited XML queries from another system or an older codebase, keeping them in XPath can also reduce translation mistakes. In contrast, if the query is being built by new C# code from scratch, LINQ to XML is often easier to refactor safely.

You can also use XPathEvaluate when the result is not a simple element selection, such as a count or a boolean expression. That makes XPath useful for quick checks as well as node retrieval.

For example, an existence check can be easier to express in XPath than in a larger LINQ projection when you only need a yes-or-no answer from the XML.

Common Pitfalls

  • Forgetting using System.Xml.XPath;, which makes the extension methods appear to be missing.
  • Writing namespace-unaware XPath against namespaced XML.
  • Expecting XPath results to be strongly typed beyond XElement, IEnumerable<XElement>, or general evaluation objects.
  • Using XPath for everything when a straightforward LINQ to XML query would be clearer in C#.

Summary

  • 'XDocument can use XPath through extension methods in System.Xml.XPath.'
  • 'XPathSelectElement and XPathSelectElements are the most common entry points.'
  • XPath works well for compact XML filtering expressions.
  • Namespaced XML requires an XmlNamespaceManager.
  • LINQ to XML is often more idiomatic, but XPath is still useful when it fits the query better.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.