相关疑难解决方法(0)

如何在XElement或LINQ中使用XPath?

考虑以下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>
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种非常简短的方法来获得<hash>元素的价值.我试过了:

var hash = xml.Element("hash").Value;
Run Code Online (Sandbox Code Playgroud)

但那不起作用.是否可以提供XPath查询XElement?我可以使用旧System.Xml框架来执行此操作,执行以下操作:

xml.Node("/response/data/hash").Value
Run Code Online (Sandbox Code Playgroud)

在LINQ命名空间中是否有这样的东西?


更新:

在对此进行了一些讨论之后,我找到了一种方法来做我正在尝试做的事情:

var hash = xml.Descendants("hash").FirstOrDefault().Value;
Run Code Online (Sandbox Code Playgroud)

我仍然有兴趣看看是否有人有更好的解决方案?

.net xml xelement xpath linq-to-xml

76
推荐指数
4
解决办法
6万
查看次数

标签 统计

.net ×1

linq-to-xml ×1

xelement ×1

xml ×1

xpath ×1