从 XDocument 获取 XElement

BWA*_*BWA 1 c# xml linq-to-xml

我有 XML

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
...
Run Code Online (Sandbox Code Playgroud)

我将 xml 加载到 XDocument

XDocument xDoc = XDocument.Parse(xmlString);
Run Code Online (Sandbox Code Playgroud)

接下来我尝试找到XElement包含正文

我试过

XElement bodyElement = xDoc.Descendants(XName.Get("Body", "s")).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

或者

XElement bodyElement = xDoc.Descendants("Body").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

或者

XElement bodyElement = xDoc.Elements("Body").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

bodyElement始终是null

如果我尝试添加命名空间

XElement bodyElement = xDoc.Descendants("s:Body").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

我有一个关于:.

如果我从 XML 中删除s

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
...
Run Code Online (Sandbox Code Playgroud)

一切正常。

如何获得XElement包含Body

Jon*_*eet 6

您正在尝试查看 URI 为“s”的命名空间 - 它没有该 URI。URI 是"http://schemas.xmlsoap.org/soap/envelope/". 我还建议避免XName.Get使用XNamespaceXName +(XNamespace, string)操作符:

XNamespace s = "http://schemas.xmlsoap.org/soap/envelope/";
XElement body = xDoc.Descendants(s + "Body").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)