Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 276
Paul Fryer Avatar asked Sep 04 '10 15:09

Paul Fryer


People also ask

What is XPath in C#?

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.

What is XPathSelectElement?

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.


1 Answers

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"); 
like image 177
Richard Avatar answered Sep 21 '22 00:09

Richard