如何使用XPath用的XElement或LINQ?如何使用、XPath、LINQ、XElement

2023-09-02 10:43:39 作者:゛如果還有今天

考虑下面的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>

我在寻找一个非常短的方式来获得&LT的只是价值;散&GT; 元素。我想:

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

但是,这不是工作。是否有可能提供一个XPath查询到的XElement ?我能做到这一点的老的System.Xml 框架下,做一些这样的:

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

有没有这样的事情在LINQ命名空间?

Is there something like this in a LINQ namespace?

更新:

胡闹围绕这一一些我找到了一种方法做我想要做后:

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?

推荐答案

要使用XPath使用LINQ到XML的 System.Xml.XPath 添加一个using声明,这将带来的System.Xml.XPath.Extensions为范围。

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.

在您的例子:

var value = (string)xml.XPathEvaluate("/response/data/hash");