CSharp - Querying XML with XPath Syntax

Introduction

You can use XPath via System.Xml.XPath.Extensions class in the System.Xml.XPath namespace.

This class adds XPath search capability via extension methods.

The following code created our typical XML document.

We called the XPathSelectElement method on the document and provided an XPath search expression to find the Book element whose FirstName element's value is "Joe".

Using the XPath extension methods, you can obtain a reference to a System.Xml.XPath.XPathNavigator object to navigate your XML document, perform an XPath query to return an element or sequence of elements, or evaluate an XPath query expression.

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;

class Program/*from   ww  w. j av  a2  s .co  m*/
{
    static void Main(string[] args)
    {
        XDocument xDocument = new XDocument(
      new XElement("Books",
        new XElement("Book",
          new XAttribute("type", "Author"),
          new XElement("FirstName", "Joe"),
          new XElement("LastName", "Ruby")),
        new XElement("Book",
          new XAttribute("type", "Editor"),
          new XElement("FirstName", "PHP"),
          new XElement("LastName", "Python"))));

        XElement bookParticipant = xDocument.XPathSelectElement(
          "//Books/Book[FirstName='Joe']");

        Console.WriteLine(bookParticipant);
    }
}

Result