Pau*_*yer 76 .net xml xelement xpath linq-to-xml
考虑以下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)
我仍然有兴趣看看是否有人有更好的解决方案?
Ric*_*ard 134
要使用带有LINQ to XML的XPath添加一个using声明System.Xml.XPath,这将把扩展方法System.Xml.XPath.Extensions带入范围.
在你的例子中:
var value = (string)xml.XPathEvaluate("/response/data/hash");
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 38
其他人完全合理地建议如何使用"本机"LINQ到XML查询来做你想要的.
然而,在提供大量替代的利益,考虑XPathSelectElement,XPathSelectElements并XPathEvaluate评估对一个XPath表达式XNode(他们所有的扩展方法XNode).您还可以使用CreateNavigator创建XPathNavigator一个XNode.
就个人而言,我是直接使用LINQ to XML API的忠实粉丝,因为我是一个很大的LINQ粉丝,但如果你对XPath更熟悉,上面的内容可能对你有所帮助.
abh*_*hek 14
在处理LINQ to XML时,为什么不使用LINQ来获取实际对象.
后代从整个XML中查找每个元素,并列出与指定名称匹配的所有对象.所以在你的情况下,hash是它找到的名字.
所以,而不是做
var hash = xml.Descendants("hash").FirstOrDefault().Value;
Run Code Online (Sandbox Code Playgroud)
我会像以下一样分手:
var elements = xml.Descendants("hash");
var hash = elements.FirstOrDefault();
if(hash != null)
hash.Value // as hash can be null when default.
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您还可以获得属性,节点元素等.
查看这篇文章以清楚地了解它,以便它有所帮助. http://www.codeproject.com/KB/linq/LINQtoXML.aspx 我希望这会对你有所帮助.
您可以使用.Element()方法链接元素以形成类似XPath的结构.
对于你的例子:
XElement xml = XElement.Parse(@"...your xml...");
XElement hash = xml.Element("data").Element("hash");
Run Code Online (Sandbox Code Playgroud)