XmlSerializer Performance Issue when Specifying XmlRootAttribute

后端 未结 4 832
余生分开走
余生分开走 2020-12-01 08:17

I\'m currently having a really weird issue and I can\'t seem to figure out how to resolve it.

I\'ve got a fairly complex type which I\'m trying to serialize

4条回答
  •  猫巷女王i
    2020-12-01 08:44

    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 cache =
                                new Dictionary();
    
        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!

提交回复
热议问题