【问题标题】:XmlSerializer constructor with XmlTypeMapping and XmlRootAttribute arguments带有 XmlTypeMapping 和 XmlRootAttribute 参数的 XmlSerializer 构造函数
【发布时间】:2011-11-27 16:42:43
【问题描述】:

我想在 C# 中预取一组已知类类型的 XmlTypeMapping,以加快它们的 XML 反序列化,同时将新的 XmlSerializer 实例化为 XmlReflectionImporter.ImportTypeMapping(发生在 XmlSerializer 构造上类类型)非常耗时,并且似乎发生在每个 XmlSerializer 构造中。

此外,我正在解析的 xml 内容迫使我使用 XmlRootAttribute 参数来设置要解析的 xml 根元素名称,因为它并不总是相同的。为此,我可以使用XmlSerializer(Type, XmlRootAttribute) 构造函数来反序列化我的对象。

但是,我也想从预取 XmlTypeMapping 中受益,但我看不到任何 XmlSerializer 构造函数,例如:XmlSerializer( XmlTypeMapping, XmlRootAttribute ) 或类似的东西。我怎样才能做到这一点?

任何帮助将不胜感激!谢谢。

【问题讨论】:

  • 该构造函数的另一个缺点是它将运行时生成的反序列化程序集保留在内存中,无法释放

标签: c# .net xml serialization deserialization


【解决方案1】:

内置缓存不用于任何接受 XmlRootAttribute 的构造函数。最好的办法是使用接受单个 XmlTypeMapping 参数的构造函数:

public XmlSerializer(XmlTypeMapping xmlTypeMapping)

并将其包装在您自己的接受 XmlRootAttribute 的构造函数中,并使用 XmlReflectionImporter 从中构造 XmlTypeMapping:

public class CachedRootXmlSerializer : XmlSerializer
{
    private static Dictionary<int, XmlTypeMapping> rootMapCache = new Dictionary<int,XmlTypeMapping>();

    private static XmlTypeMapping GetXmlTypeMappingFromRoot(Type type, XmlRootAttribute xmlRootAttribute)
    {
        XmlTypeMapping result = null;
        int hash = 17;

        unchecked
        {
            hash = hash * 31 + type.GUID.GetHashCode();
            hash = hash * 31 + xmlRootAttribute.GetHashCode();
        }

        lock (rootMapCache)
        {
            if (!rootMapCache.ContainsKey(hash))
            {
                XmlReflectionImporter importer = new XmlReflectionImporter(null, null);
                rootMapCache[hash] = importer.ImportTypeMapping(type, xmlRootAttribute, null);
            }
            result = rootMapCache[hash];
        }

        return result;
    }

    CachedRootXmlSerializer(Type type, XmlRootAttribute xmlRootAttribute)
        : base(GetXmlTypeMappingFromRoot(type, xmlRootAttribute))
    {
    }
}

享受吧!

【讨论】:

  • 谢谢,这真的很聪明。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 2017-04-21
  • 2018-06-03
  • 1970-01-01
  • 2016-04-16
相关资源
最近更新 更多