XmlSerializer构造函数,包含XmlTypeMapping和XmlRootAttribute参数

dle*_*eun 7 .net c# xml serialization deserialization

我想在C#中预取XmlTypeMapping一个已知类类型的C#来加速它们的XML反序列化,同时实例化一个新的XmlSerializeras XmlReflectionImporter.ImportTypeMapping(在XmlSerializer类类型的构造期间发生)非常耗时并且似乎在每个XmlSerializer构造中都会发生.

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

但是我也想从prefetch中受益XmlTypeMapping,我看不到任何XmlSerializer构造函数:XmlSerializer( XmlTypeMapping, XmlRootAttribute )或者接近的东西.我怎么能实现这一目标?

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

Dav*_*xas 3

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

public XmlSerializer(XmlTypeMapping xmlTypeMapping)
Run Code Online (Sandbox Code Playgroud)

并将其包装在您自己的接受 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))
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

享受!