序列化为 XML 并包含序列化对象的类型

2023-12-23

在之前的一个问题中将对象序列化为XmlDocument in C# https://stackoverflow.com/questions/781442/serialise-object-to-xmldocument,我需要将一些故障信息序列化到XmlDocument这是从 asmx 风格的 Web 服务调用返回的。在客户端我需要反序列化XmlDocument回到一个物体。

如果您知道类型,这就足够简单了,但我意识到我想要一种灵活的方法,其中要反序列化的类型也编码在XmlDocument。我目前正在通过添加手动执行此操作XmlNode to the XmlDocument具有类型名称,计算如下:

    Type type = fault.GetType();
    string assemblyName = type.Assembly.FullName;

    // Strip off the version and culture info
    assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(",")).Trim();

    string typeName = type.FullName + ", " + assemblyName;

然后在客户端上我首先从XmlDocument,并创建传递到的类型对象XmlSerialiser thus:

        object fault;
        XmlNode faultNode = e.Detail.FirstChild;
        XmlNode faultTypeNode = faultNode.NextSibling;

        // The typename of the fault type is the inner xml of the first node
        string typeName = faultTypeNode.InnerXml;
        Type faultType = Type.GetType(typeName);

        // The serialised data for the fault is the second node
        using (var stream = new StringReader(faultNode.OuterXml))
        {
            var serialiser = new XmlSerializer(faultType);
            objectThatWasSerialised = serialiser.Deserialize(stream);
        }

        return (CastToType)fault;

所以这是一种蛮力方法,我想知道是否有一个更优雅的解决方案,以某种方式自动包含序列化类型的类型名,而不是在其他地方手动记录它?


我遇到了类似的问题,并提出了相同的解决方案。就我而言,这是在 XML 序列化中将类型与值保持在一起的唯一方法。

我看到你和我一样正在削减汇编版本。但我想提一下,您会遇到泛型类型的麻烦,因为它们的签名如下所示:

System.Nullable`1[[System.Int, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

所以我做了一个函数来只删除程序集版本,这似乎足以消除版本控制问题:

    private static string CutOutVersionNumbers(string fullTypeName)
    {
        string shortTypeName = fullTypeName;
        var versionIndex = shortTypeName.IndexOf("Version");
        while (versionIndex != -1)
        {
            int commaIndex = shortTypeName.IndexOf(",", versionIndex);
            shortTypeName = shortTypeName.Remove(versionIndex, commaIndex - versionIndex + 1);
            versionIndex = shortTypeName.IndexOf("Version");
        }
        return shortTypeName;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

序列化为 XML 并包含序列化对象的类型 的相关文章

随机推荐