Linq to XML - 提取单个元素

kit*_*awk 4 c# xml linq

我有一个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>
Run Code Online (Sandbox Code Playgroud)

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

XElement responseXml = XElement.Load(responseOutputFile);
string data = responseXml.Element("SendDataResult").Value;
Run Code Online (Sandbox Code Playgroud)

需要做什么来提取SendDataResult元素.

Jon*_*eet 5

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

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

或者,直接导航:

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;
Run Code Online (Sandbox Code Playgroud)