Linq to XML - 提取单个元素

4

我有一个长这样的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元素。
1个回答

5
您可以使用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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接