使用 LINQ to XML 获取特定的后代节点值

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(); 

但是,我收到以下错误..

The '/' character, hexadecimal value 0x2F, cannot be included in a name.

试试这个代码:

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();