如何使用XPath用的XElement或LINQ? [英] How to use XPath with XElement or LINQ?

查看:535
本文介绍了如何使用XPath用的XElement或LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的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声明,这将带来的<一个扩展方法href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.extensions_methods.aspx"><$c$c>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");

这篇关于如何使用XPath用的XElement或LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆