.netxmlxpathlinq-to-xmlxelement

How to use XPath with XElement or LINQ?


Consider the following XML:

<response>
  <status_code>200</status_code>
  <status_txt>OK</status_txt>
  <data>
    <url>http://bit.ly/b47LVi</url>
    <hash>b47LVi</hash>
    <global_hash>9EJa3m</global_hash>
    <long_url>http://www.tumblr.com/docs/en/api#api_write</long_url>
    <new_hash>0</new_hash>
  </data>
</response>

I'm looking for a really short way to get just the value of the <hash> element. I tried:

var hash = xml.Element("hash").Value;

But that's not working. Is it possible to provide an XPath query to an XElement? I can do it with the older System.Xml framework, doing something like:

xml.Node("/response/data/hash").Value

Is there something like this in a LINQ namespace?


UPDATE:

After monkeying around with this some more I found a way to do what I'm trying to do:

var hash = xml.Descendants("hash").FirstOrDefault().Value;

I'd still be interested to see if anyone has a better solution?


Solution

  • 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");
    

    Note that there are other methods provided by this class, such as XPathSelectElement() which returns an XElement?.