【问题标题】:Linq to XML - Extract Single ElementLinq to XML - 提取单个元素
【发布时间】:2011-07-19 18:53:20
【问题描述】:

我有一个如下所示的 XML/Soap 文件:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <SendData xmlns="http://stuff.com/stuff">
      <SendDataResult>True</SendDataResult>
    </SendData>
  </soap:Body>
</soap:Envelope>

我想提取 SendDataResult 值,但使用以下代码和我尝试过的各种其他方法很难做到这一点。即使元素中有值,它也总是返回 null。

XElement responseXml = XElement.Load(responseOutputFile);
string data = responseXml.Element("SendDataResult").Value;

提取 SendDataResult 元素需要做什么。

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    您可以使用Descendants 后跟FirstSingle - 目前您正在询问顶级 元素它下面是否有一个SendDataResult 元素,它没有不。此外,您没有使用正确的命名空间。这应该可以解决它:

    XNamespace stuff = "http://stuff.com/stuff";
    string data = responseXml.Descendants(stuff + "SendDataResult")
                             .Single()
                             .Value;
    

    或者,直接导航:

    XNamespace stuff = "http://stuff.com/stuff";
    XNamespace soap = "http://www.w3.org/2003/05/soap-envelope";
    string data = responseXml.Element(soap + "Body")
                             .Element(stuff + "SendDataResult")
                             .Value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多