2

I have a method which takes an object and turns it into a string of XML. This works great but I want the output XML to include the data type of object properties (string, int, double, etc). I've searched high and low but I can't seem to find a solution without writing a custom serializer.

Any help would be most appreciated.

private static string ToXML<t>(t obj, bool indent = false)
{
    System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
    XmlSerializer xs = new XmlSerializer(typeof(t));
    StringBuilder sbuilder = new StringBuilder();
    var xmlws = new System.Xml.XmlWriterSettings() {OmitXmlDeclaration = true, Indent = indent};

    ns.Add(string.Empty, string.Empty);

    using (var writer = System.Xml.XmlWriter.Create(sbuilder, xmlws))
    {
        xs.Serialize(writer, obj, ns);
    }

    string result = sbuilder.ToString();

    ns = null;
    xs = null;
    sbuilder = null;
    xmlws = null;

    return result;
}
Daniel Knoodle
  • 384
  • 1
  • 4
  • 1
    Also, a style suggestion - use uppercase letters, or identifiers which start with an uppercase letter, to represent type parameters to generics. This is the recommended practice by Microsoft for good reason; at a glance, readers of your code know that 'T' is the type parameter passed into your method, as opposed to an object itself. – RyanR Jun 25 '11 at 04:18
  • 1
    btw, in C# you don't need to assign your locals to `null`.... – Marc Gravell Jun 25 '11 at 07:36

1 Answers1

1

The XmlSerializer in .NET is designed to work with itself to re-serialize using the concrete object type to determine how it should treat the data from XML.

The standard XmlSerializer will not serialize that information for you.

You should look into the DataContractSerializer from WCF, from what I remember it's much more verbose and assumes less. It's also very flexible.

Aren
  • 54,668
  • 9
  • 68
  • 101