Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a value type cast as an object to a string using XmlConvert?

Tags:

c#

xml

I'm looking for something equivalent to the code below but for any value type without having to encode a switch statement for each data type. The code below does not compile because XmlConvert.ToString() does not have an overload that accepts and object.

        int intValue = 10;
        object boxedValue = (object)intValue;
        string xmlValue = XmlConvert.ToString(boxedValue);

In other words, is there a better way than this:

public static string ToXmlString(Type type, object value) {

        switch(Type.GetTypeCode(type)) {
            case TypeCode.Int32:
                return XmlConvert.ToString((int) value);
            case TypeCode.DateTime:
                return XmlConvert.ToString((DateTime) value, XmlDateTimeSerializationMode.Unspecified);
            case TypeCode.Boolean:
                return XmlConvert.ToString((bool) value);

            // TODO:  Add case for all other value types!

            default:
                return value.ToString();
        }
    }
like image 239
Darrel Miller Avatar asked Jan 26 '09 01:01

Darrel Miller


1 Answers

All value types are inherently serializable. So you just need to use an XMLSerializer. Something like this would do it (based on your method):

public static string ToXmlString(Type type, object value)
{
    StringBuilder sb = new StringBuilder();
    System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb);
    System.Xml.Serialization.XmlSerializer serial = 
        new System.Xml.Serialization.XmlSerializer(type);
    serial.Serialize(writer, value);
}
like image 180
DarkwingDuck Avatar answered Oct 29 '22 15:10

DarkwingDuck