【问题标题】:Extract XML from SOAP envelope in c#从 C# 中的 SOAP 信封中提取 XML
【发布时间】:2015-05-30 20:21:21
【问题描述】:

我在 SOAP 信封中收到来自 Web 服务的响应,如下所示:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
  <ProcessTranResponse xmlns="http://www.polaris.co.uk/XRTEService/2009/03/">
    <ProcessTranResult xmlns:a="http://schemas.datacontract.org/2004/07/XRTEService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <a:PrintFormFileNameContents i:nil="true"/>
      <a:ResponseXML>response_message</a:ResponseXML>
    </ProcessTranResult>
  </ProcessTranResponse>
</s:Body>

我想将response_message 获取到一个字符串变量。我试过做

XDocument doc = XDocument.Parse(Response);
XNamespace xmlnsa = "http://schemas.datacontract.org/2004/07/XRTEService";
var ResponseXML = doc.Descendants(xmlnsa + "ResponseXML");

当我使用手表时,我在 ResponseXML -&gt; Results View[0] -&gt; Valueresponse_message 中看到,但我无法弄清楚从 C# 获取 Value 的下一步是什么。

【问题讨论】:

    标签: c# xml soap


    【解决方案1】:

    XContainer.Descendants 返回元素的集合。然后你应该尝试这样的事情:

    foreach (XElement el in ResponseXML)
    {
        Console.WriteLine(el.Value);
    }
    

    如果你知道总是只有一个响应,你也可以这样做:

    XDocument doc = XDocument.Parse(Response);
    
    XNamespace xmlnsa = "http://schemas.datacontract.org/2004/07/XRTEService";
    
    XElement ResponseXML = (from xml in XMLDoc.Descendants(xmlnsa + "ResponseXML")
                            select xml).FirstOrDefault();
    
    string ResponseAsString = ResponseXML.Value;
    

    【讨论】:

    • 还有 doc.Descendants(xmlnsa + "ResponseXML").First().Value;使用 Linq 有效。谢谢!
    • 不客气!请注意,如果后代列表为空,.First() 可能会抛出异常...
    • 如果FirstOrDefault返回nullResponseXML.Value会抛出异常。
    【解决方案2】:

    您可以采用多种解决方案来满足您的目的,而您可能想介绍或不介绍 xml 内容的结构。

    静态态度

    你可以简单地使用这个:

    XmlDocument _doc = new XmlDocument();
    doc.LoadXml(_stream.ReadToEnd());
    

    然后通过以下方式找到所需的数据:

    doc.LastChild.FirstChild.FirstChild.LastChild.InnerText;
    

    读取xml结构

    您可以编写一些额外的代码行来引入命名空间和其他 xml 内容以查找/映射可用数据,请查看 extracting-data-from-a-complex-xml-with-linq

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多