我有一个如下所示的 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 元素需要做什么。
最佳答案
您可以使用 Descendants
后接 First
或 Single
- 目前您正在询问顶级元素它的正下方是否有一个 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;
关于c# - Linq to XML - 提取单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6752505/