【问题标题】:Using LINQ to XML to get specific descendants node value使用 LINQ to XML 获取特定的后代节点值
【发布时间】:2018-01-11 16:18:48
【问题描述】:

我尝试使用 LINQ to XML 查询一个 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>

我正在尝试读取节点&lt;status&gt; 的值以确定API 调用是否成功。我无法将获取 &lt;status 节点值所需的 LINQ 语法放在一起。我想我可以使用 XPath 语法来获取值。

XDocument xml = XDocument.Parse(xmlResponse);
string returnValue = = xml.Descendants("result/status").Select(x => x.Name).ToString(); 

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

“/”字符,十六进制值 0x2F,不能包含在名称中。

【问题讨论】:

  • xml.Descendants("status).Where(n =&gt; n.Parent.LocalName = "result")xml.Descendants("result").Elements("result")

标签: c# xml linq-to-xml


【解决方案1】:

试试这个代码:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      相关资源
      最近更新 更多