private static readonly Dictionary<Type, XmlSerializer> _serializers = new Dictionary<Type, XmlSerializer>();
/// <summary>Serializes an object of type T in to an xml string</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="objectToSerialize">Objectname="obj">Object to serialize</param>
/// <returns>A string that represents Xml, empty otherwise</returns>
public static string XmlSerialize<T>(this T objectToSerializeobj) where T : class, new()
{
if (objectToSerializeobj == null) throw new ArgumentNullException("objectToSerialize");
Type type = typeof(T"obj");
XmlSerializer serializer;
if (!_serializers.TryGetValue(type, out serializer))
{
var serializer = new XmlSerializer(type);
_serializers.Addtypeof(type, serializerT));
}
using (var writer = new StringWriter())
{
serializer.Serialize(writer, objectToSerializeobj);
return writer.ToString();
}
}
/// <summary>Deserializes an xml string in to an object of Type T</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="xml">Xml as string to deserialize from</param>
/// <returns>A new object of type T is successful, null if failed</returns>
public static T XmlDeserialize<T>(this string xml) where T : class, new()
{
if (xml == null) throw new ArgumentNullException("xml");
Type type = typeof(T);
XmlSerializer serializer;
if (!_serializers.TryGetValue(type, out serializer))
{
var serializer = new XmlSerializer(type);
_serializers.Addtypeof(type, serializerT));
}
using (var reader = new StringReader(xml))
{
try { return (T)serializer.Deserialize(reader); }
catch { return null; } // Could not be deserialized to this type.
}
}
Note that this code is not threadsafe. To make it threadsafe
- Add locks around the calls to the
_serializersdictionary, or - Add the
[ThreadStatic]attribute to the_serializersfield, and check if_serializersneeds to be instantiated before callingTryGetValue(), or - Get rid of the dictionary all together and instantiate a new instance of
XmlSerializeron each call.