Deserializing/Serializing SOAP Messages in C#

   /// <summary>
   /// Converts a SOAP string to an object
   /// </summary>
   /// <typeparam name="T">Object type</typeparam>
   /// <param name="SOAP">SOAP string</param>
   /// <returns>The object of the specified type</returns>
   public static T SOAPToObject<T>(string SOAP)
   {
       if (string.IsNullOrEmpty(SOAP))
      {
          throw new ArgumentException("SOAP can not be null/empty");
      }

      using (MemoryStream Stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(SOAP)))
      {
          SoapFormatter Formatter = new SoapFormatter();

          return (T)Formatter.Deserialize(Stream);
      }
  }
  

  /// <summary>
  /// Converts an object to a SOAP string
  /// </summary>
  /// <param name="Object">Object to serialize</param>
  /// <returns>The serialized string</returns>
  public static string ObjectToSOAP(object Object)
  {
      if (Object == null)
      {
          throw new ArgumentException("Object can not be null");
      }

      using (MemoryStream Stream = new MemoryStream())
      {
          SoapFormatter Serializer = new SoapFormatter();
          Serializer.Serialize(Stream, Object);
          Stream.Flush();

          return UTF8Encoding.UTF8.GetString(Stream.GetBuffer(), 0, (int)Stream.Position);
      }
  }

原文地址:https://www.cnblogs.com/fery/p/3490813.html