quick object-to-xml serializer

2008-09-04 @ 14:11#

i am currently on a project to integrate data from a major partner site into our web application. i'm bummed that the partner is using SOAP instead of HTTP/REST. oh, well.

one of the things i don't like about SOAP is that tight binding between URLs and the methods/classes in the code. change a method name - the URL(s) change. change an underlying class that is passed between client and server - both the client and server code must be recompiled. using the HTTP document body does not always mean changes 'break' the client or server. this is especially true when you use the accepts and content-type headers properly. but i rant on...

the real point of this post is to pass along a short snippet of code that i rely upon to convert tightly bound SOAP classes into plain XML for use within our local apps. the (C#) code below will take any serialize-able object and convert it into an XML string pile. you can use the output of this method to load an XmlDocument for further processing.

// serialize object to (xml) string
private string SerializeObject(object obj)
{
    StringWriter sw = new StringWriter(new StringBuilder());
    XmlSerializer xs = new XmlSerializer(obj.GetType());
    xs.Serialize(sw, obj);

    return sw.ToString();
}

// convert object to XML string and load into XmlDocument
private void Sample()
{
    Contract c = new Contract();
    XmlDocument d = new XmlDocument();

    d.LoadXml(SerializeObject(c));
}

code