Deserializing/Serializing SOAP Messages in C#

For all those apps built 20 years ago.
Jul 24 2009 by James Craig

For those of you that don't know what SOAP is, SOAP is an XML based syntax that allows programs communicate with one another. In other words, just like RSS, etc. it is just another XML document with specific syntax. There really isn't much to it, but serializing/deserializing them can be a pain. Luckily for us .Net has a built in class for us. Specifically in the System.Runtime.Serialization.Formatters.Soap namespace (you may need to add a reference to it). So let's look at how to use this class:

  /// <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);
}
}

It's pretty simple and if you've done XML or binary serialization in .Net, it's going to look fairly similar. Anyway, I can't believe how long it took me before I ran into a project that actually required SOAP. But I finally ran into one and decided to go about writing a couple of generic functions to help me out in serializing and deserializing the objects and will hopefully help you out as well. So try it out, leave feedback, and happy coding.