[英]Using LINQ to XML to get specific descendants node value
我有一个XML文档,我正在尝试使用LINQ to XML查询。 XML是..
<?xml version="1.0" encoding="UTF-8"?>
<response>
<operation>
<authentication>
<username>redacted</username>
<isauthenticated>true</<isauthenticated>>
</authentication>
<result>
<status>success</status>
<other-elements></<other-elements>
<other-elements></<other-elements>
<other-elements>
<other-sub-elements></other-sub-elements>
<other-sub-elements></other-sub-elements>
</<other-elements>
</result>
</operation>
</response>
我正在尝试读取节点<status>
的值以确定API调用是否成功。 我在整理获取<status
节点的值所需的LINQ语法时遇到麻烦。 我以为可以使用XPath语法来获取值。
XDocument xml = XDocument.Parse(xmlResponse);
string returnValue = = xml.Descendants("result/status").Select(x => x.Name).ToString();
但是,我收到以下错误..
名称中不能包含'/'字符(十六进制值0x2F)。
试试这个代码:
XDocument xdoc = XDocument.Parse(@"
<response>
<operation>
<authentication>
<username>redacted</username>
<isauthenticated>true</isauthenticated>
</authentication>
<result>
<status>success</status>
</result>
</operation>
</response>
");
Boolean isSuccess;
String s = xdoc.Element("response").Element("operation").Element("result").Element("status").Value;
isSuccess = s == "success";
它获取status
元素的值并检查其是否等于特定值; 在这种情况下, isSuccess
将为true
。
LINQ-to-XML方法Elements()
和Descendants()
仅处理单个名称,而不处理类似xpath的路径。 如果要给出xpath表达式,请使用xpath扩展名。
// using System.Xml.Linq;
var status = (string)xml.XPathSelectElement("//result/status");
否则,您需要正确使用方法建立等效查询。
var status = (string)xml.Descendants("result").Elements("status").FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.