XmlSerializer Performance Issue when Specifying XmlRootAttribute

Just for anyone else who runs into this problem; armed with the answer above and the example from MSDN I managed to resolve this issue using the following class:

public static class XmlSerializerCache
{
    private static readonly Dictionary<string, XmlSerializer> cache =
                            new Dictionary<string, XmlSerializer>();

    public static XmlSerializer Create(Type type, XmlRootAttribute root)
    {
        var key = String.Format(
                  CultureInfo.InvariantCulture,
                  "{0}:{1}",
                  type,
                  root.ElementName);

        if (!cache.ContainsKey(key))
        {
            cache.Add(key, new XmlSerializer(type, root));
        }

        return cache[key];
    }
}

Then instead of using the default XmlSerializer constructor which takes an XmlRootAttribute, I use the following instead:

var xmlRootAttribute = new XmlRootAttribute("ExampleElement");
var serializer = XmlSerializerCache.Create(target.GetType(), xmlRootAttribute);

My application is now performing again!

Leave a Comment