How to use XPath with XElement or LINQ?
To use XPath with LINQ to XML add a using declaration for System.Xml.XPath
, this will bring the extension methods of System.Xml.XPath.Extensions
into scope.
In your example:
var value = (string)xml.XPathEvaluate("/response/data/hash");
Others have entirely reasonably suggested how to use "native" LINQ to XML queries to do what you want.
However, in the interests of providing lots of alternatives, consider XPathSelectElement
, XPathSelectElements
and XPathEvaluate
to evaluate XPath expressions against an XNode
(they're all extension methods on XNode
). You can also use CreateNavigator
to create an XPathNavigator
for an XNode
.
Personally I'm a big fan of using the LINQ to XML API directly, as I'm a big LINQ fan, but if you're more comfortable with XPath, the above may help you.