views:

122

answers:

3

Consider the following XML:

<response>
  <status_code>200</status_code>
  <status_txt>OK</status_txt>
  <data>
    <url>http://bit.ly/b47LVi&lt;/url&gt;
    <hash>b47LVi</hash>
    <global_hash>9EJa3m</global_hash>
    <long_url>http://www.tumblr.com/docs/en/api#api_write&lt;/long_url&gt;
    <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?

+2  A: 

See, when dealing with LINQ to XML why dont you use LINQ to get the actual object.

Descendants find each element from the whole XML and lists all the objects that matches the name specified. So in your case hash is the name which it finds.

So, rather than doing var hash = xml.Descendants("hash").FirstOrDefault().Value;

I would break apart like :

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

if(hash != null)
 hash.Value // as hash can be null when default. 

In this way you might also get attributes, nodes elements etc.

Check this article to get clear idea about it so that it helps. http://www.codeproject.com/KB/linq/LINQtoXML.aspx I hope this will help you.

abhishek
@adhishek +1 for explaining the value of separating the element to it's own variable so you can do other stuff like get attributes, etc..
Paul Fryer
+2  A: 

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.

Jon Skeet
+3  A: 

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");
Richard
OK, seems closest to the original question
Henk Holterman