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?
The XML Document Object Model (DOM) contains methods that allow you to use XML Path Language (XPath) navigation to query information in the DOM. You can use XPath to find a single, specific node or to find all nodes that match some criteria.
XPathSelectElement(XNode, String) Selects an XElement using a XPath expression. XPathSelectElement(XNode, String, IXmlNamespaceResolver) Selects an XElement using a XPath expression, resolving namespace prefixes using the specified IXmlNamespaceResolver.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With