How can I query an XDocument with a 'path'?

binncheol picture binncheol · Jun 27, 2012 · Viewed 17.1k times · Source

I would like to query an XDocument object for a given path, (e.g. "/path/to/element/I/want") but I don't know how to proceed.

Answer

svick picture svick · Jun 27, 2012

You can use methods from System.Xml.XPath.Extensions to do this.

For example, if you want to select a single element, you would use XPathSelectElement():

var element = doc.XPathSelectElement("/path/to/element/I/want");

The queries don't have to be simple paths like what you described, they use the XPath language.