2011-09-15

Adding a ToXmlString() extension method to all objects so that they may be viewed as Xml when debugging

Working with soap Request and Response objects I have found that it is a nice thing to be able to check the request, and copy it into SoapUI to test what really is going on. So my first thought was to create an extension method and put it on all my request objects, but it takes some work, so I went for the lazy solution: add extension method on System.Object. Now this may not work on all objects, I think they need to be serializable at least, but it seems to work on my request objects. So here’s my code, just use it with caution, as it may have side effects:

using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

public static class ExtensionMethods
{
    public static string ToXmlString(this System.Object obj) { return serializeObject(obj); }
   
    private static string serializeObject(object obj)
    {
        XmlSerializer xs = new XmlSerializer(obj.GetType());
        StringWriter sw = new StringWriter();
        XmlTextWriter w = new XmlTextWriter(sw);
        w.Formatting = Formatting.Indented;
        w.Indentation = 3;

        xs.Serialize(w, obj);
        w.Flush();
        w.Close();

        return sw.ToString();
    }
}

 

No comments:

Post a Comment