tags:

views:

405

answers:

3

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();
        }
    }
A: 

Just to throw this out there, are you attempting to convert a business object into XML?

Perhaps you might want to look at XmlSerialization. If you mark some attributes on your business object .Net will do all the fancy XML stuff for you :).

Also, is there any reason why you are boxing your value? XmlConvert.ToString() has 19 overloads, many of which take primitives.

Spence
I appreciate the heads up, but I've been through XmlSerializer, DataContractSerializer hell. I've even played with XamlWriter. My values are boxed because I am accessing them through an Interface that deals with many datatypes.
Darrel Miller
A: 

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);
}
DarkwingDuck
The funny thing is if you use Reflector to trace into XmlSerializer.Serialize you eventually hit a method called SerializePrimitive which has a big switch statement that dispatches to methods that eventually call XmlConvert.ToString where they cast the object to the native type.
Darrel Miller
But is this a bad thing? All that's happening is that the switch is moved from your code into framework code.
DarkwingDuck
A: 

Another option is to use Reflector to look at then make a copy of System.Xml.Linq.XContainer.GetStringValue (it's internal unfortunatly)