c# - Linq to XML - 提取单个元素

标签 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>

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

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

提取 SendDataResult 元素需要做什么。

最佳答案

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

关于c# - Linq to XML - 提取单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6752505/

相关文章:

c# - 使用 LINQ toSQL 从存储过程返回新插入的行 ID

c# - 如何在 C# 中的 XML 序列化期间交替 XML 元素?

c# - 反序列化对象列表的问题

xml - 如何引用自己创建的 xsd

java - 将 xml 转换为 json 而不转换字符串/整数?

c# - Linq 查询以列形式返回国家/地区,以行形式返回城市并在单元格中计数

c# - 不同的 linq 使用顺序之间有性能差异吗?

c# - 使用语句的格式/缩进 (C#)

c# - 线程应用问题

c# - 在 SQL 中克隆带有主键的行?