Complete control over XML in WCF

Sometimes it is needed to have complete control over how WCF manipulates the data being returned. By default, WCF serializes objects and returns them as XML. Sadly, there is not much control on how to create templates over how objects will be serialized (flat structure, hierarchical, etc). In many cases this does not matter. A few weeks ago I stumbled for the first time when I need 100% control over how the XML was formated and being sent.

To send custom formated XML use the message envelope and not the string datatype. If the envelope is not used, it will add extra meta content.

Here is how it can be done:

public Message GetMessage(string xml)
{
    XmlDocument x = new XmlDocument();

    //This is very important as it will VALIDATE the XML. Saved my butt a few times.
    x.LoadXml(xml);

    XmlElementBodyWriter writer = new XmlElementBodyWriter(x.DocumentElement);

    Message msg = Message.CreateMessage(MessageVersion.None,
                OperationContext.Current.OutgoingMessageHeaders.Action, writer);

    return msg;
}

public class XmlElementBodyWriter : BodyWriter
{
    XmlElement xmlElement;

    public XmlElementBodyWriter(XmlElement xmlElement)
                : base(true)
    {
         this.xmlElement = xmlElement;
    }

    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
         xmlElement.WriteTo(writer);
    }
 }

Also a little warning, the string passed in should be formated and already encoded in the format you want. This can make a huge difference specially when internationalization is involved.