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();
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With