XPath in C# code behind of WPF

Created : 7/11/2022

Question

You can use XPath if you're binding the XML document in the XAML, but what if you're loading the XML document dynamically in the code behind? Is there any XPath methods available in the C# code behind?

(using .NET 3.5 SP1)

Questioned by : discorax

Answer

Load the XML into a XPathDocument in your code behind, and use an XPathNavigator to hold your query. The result of the XPathNavigator.Select() is an iterator that returns the selected nodes.

Example (using System.XML and System.Xml.XPath):

XPathDocument doc = new XPathDocument(@"c:\filepath\doc.xml");
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iter = nav.Select("/xpath/query/here");

while(iter->MoveNext)
{
  //Do something with node here.
}
Answered by : Godeke