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

Nei*_*ell 5 c# xml-serialization

在上一个关于将对象序列化为XmlDocumentin C# 的问题中,我需要将一些错误信息序列化为XmlDocument从 asmx 样式的 web 服务调用返回的 。在客户端上,我需要将XmlDocument返回反序列化为一个对象。

如果您知道类型,这很简单,但我意识到我想要一种灵活的方法,其中要反序列化的类型也在XmlDocument. 我目前正在通过向具有类型名称的 中添加一个XmlNode来手动执行此操作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;
Run Code Online (Sandbox Code Playgroud)

然后在客户端上,我首先从 中取回此类型名称XmlDocument,并创建传递到XmlSerialiser因此的类型对象:

        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;
Run Code Online (Sandbox Code Playgroud)

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

Max*_*kin 4

我遇到了类似的问题,并提出了相同的解决方案。就我而言,这是在 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
Run Code Online (Sandbox Code Playgroud)

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

    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;
    }
Run Code Online (Sandbox Code Playgroud)