A pedant that hangs out in the dark corner-cases of the web.

Wednesday, June 10, 2009

Easy XML serialization of complex objects with C# 3.0

C# 3.0 Update! If you've got complex, XML-serializable objects you'd like to trace easily, such as SOAP objects, here's a handy way to dump their contents to an XML string:

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

public class XmlExporter
  /// <summary>
  /// Serialize an object as an XML string.
  /// </summary>
  /// <param name="o">The object to serialize.</param>
  /// <param name="defaultNamespace">The default XML namespace of the object (to supress noisy namspaces).</param>
  /// <returns>The object, serialized as an XML string.</returns>
  public static string ToString(object o, string defaultNamespace)
    if (o == null) return "<NULL />";
    var utf8 = new UTF8Encoding(false);
    using (var ms = new MemoryStream())
    using (var x = new XmlTextWriter(ms, utf8) {Formatting = Formatting.Indented})
      var xs = String.IsNullOrEmpty(defaultNamespace)
        ? new XmlSerializer(o.GetType())
        : new XmlSerializer(o.GetType(), defaultNamespace);
      xs.Serialize(x, o);
      return utf8.GetString(ms.GetBuffer(), 0, (int) ms.Length);


Atul Chaudhary said...

Liked it

Atul Chaudhary said...

I would like to make one point in this functionality when you create xml file from object. it creates the white spaces in the end of the file due to which Xml file get corrupted..