【问题标题】:Get Strings from SOAP Message in C#从 C# 中的 SOAP 消息中获取字符串
【发布时间】:2019-05-11 22:18:21
【问题描述】:

如何解析 SOAP 消息中的特定部分并获取它们的值?

例如,如果soap响应消息是这样的:

      <?xml version="1.0" encoding="utf-8"?>
 <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
   <soap12:Body>
     <GetCountryListResponse xmlns="http://example.org/">
       <GetCountryListResult>
         <string>string</string>
         <string>string</string>
       </GetCountryListResult>
     </GetCountryListResponse>
   </soap12:Body>
 </soap12:Envelope>

我想获取 GetCountryListResult 值并将其保存到字符串变量中。

我在 Java 中找到了一个很好的答案:

Get Strings from SOAP Message in Java

【问题讨论】:

    标签: c# asp.net .net web-services soap


    【解决方案1】:

    此示例将从文件中读取您的 xml 并构建找到的字符串列表,但您可以了解并了解如何解析它。

    using (FileStream fs = new FileStream(@"c:\temp\soap.xml", FileMode.Open))
    {
        var sr = new StreamReader(fs);
        var str = sr.ReadToEnd();
        XmlDocument document = new XmlDocument();
        document.LoadXml(str);
    
        XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
        manager.AddNamespace("soap12", "http://www.w3.org/2003/05/soap-envelope");
        manager.AddNamespace("", "http://example.org/");
        XmlNodeList xnList = document.SelectNodes("//soap12:Envelope/soap12:Body/GetCountryListResponse/GetCountryListResult", manager);
        if (xnList.Count == 0) return;
    
        XmlNode countryListResult = xnList[0];
        List<string> result = new List<string>();
        foreach (XmlNode childNode in countryListResult.ChildNodes)
        {
            result.Add(childNode.FirstChild.Value);
        }
    }
    

    您还需要添加错误处理。

    【讨论】:

      【解决方案2】:

      var service = new WebService(); var result = service.Invoke(soapAction, 方法, 参数);

      XNamespace nsSoap = "http://www.w3.org/2003/05/soap-envelope";
      XNamespace ns = "link-to-namespace";
      
      // Look for the "Fault" element in the response. If present, there was an error.
      var fault = result.Root.Element("{" + nsSoap + "}Body").Element("{" + ns_soap + "}Fault");
      if (error != null)
      {
          var codeWithNs = error.Element("{" + nsSoap + "}Code").Element("{" + ns_soap + "}Value").Value;
          var codeSplit = codeWithNs.Split(':');
          var code = codeSplit.Length == 2 ? codeSplit[1] : codeSplit[0];
          if (code == "InvalidUsernameOrPassword")
          {
              throw new InvalidUsernameOrPasswordException();
          }
          else
          {
              throw new Exception("Something went wrong.");
          }
      }
      

      【讨论】:

      • WebService 类没有 Invoke 方法。另外,您的意思是在 if 语句中输入“错误”而不是“错误”吗?
      猜你喜欢
      • 2016-09-17
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      相关资源
      最近更新 更多