我祈祷有人对 Microsoft XmlSerializer 有很好的理解。
基本上,我已经构建了一个系统用于在序列化程序的背面输出 XML,这现在给我带来了很多麻烦,我正在努力避免重大的重写。
介绍
我当前的系统使用了很多派生类。
例如,
BaseResponse -> CarParkResponse -> CarParkResponseInherited
BaseResponse 和 CarParkResponse(都在库 dll 中)与 CarParkResponseInherited 是分开的。
因此,基类会忽略派生类。
我做了什么
-> 声明派生类
我很欣赏,为了让 xmlserializer 完成它的工作,有很多方法可以声明派生类。
- 使用 XmlInclude 在基类中声明派生类
或
- 在 xmlSerialiser 中声明要序列化和反序列化的类型。例如:
XmlSerializer serializer = new XmlSerializer(typeof(CarParkResponse), new Type[] { typeof(CarParkParameters), typeof(CarParkInformation) });
我选择了后者。
我想做什么
因为派生类是独立的并且它们共享相同的属性,所以我要做的是将派生类序列化为子类。
换句话说,将 CarParkResponseInherited 反序列化为 CarParkResponse。
在“CarParkResponseInherited”中,我使用声明 XmlTypeAttribute("CarParkResponse")。
最初这会在序列化时引起问题
Types 'CarParkResponseInherited' and 'CarParkResponse' both use the XML type name, 'CarParkResponse', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type."
因为类型已经在使用“CarParkResponse”,所以我在“CarParkResponse”中声明了 XmlType(“Response”) 来解决这个问题。
问题
我现在正在尝试反序列化返回的 XML,但我现在遇到了以下问题。
The specified type was not recognized: name='CarParkResponse', namespace='', at OriginalRequest xmlns=''
令人沮丧的是,CarParkResponse 就在那里。我想知道这是否是因为我在类中使用了 XmlType("Response") 并且序列化程序没有将该类识别为 CarParkResponse 类型
所以我的问题是
基本上是否可以将派生类作为子类传递并使用 XmlSerializer 将其反序列化为子类?
我已经对生成的 xml 进行了试验。
例如,如果我不在代码中的任何地方使用序列化标记(例如 XmlType() 等)。生成的 xml 将生成一个带有“type”作为属性的 carparkresponse 元素。
值为“CarParkResponseInherited”。我已经编写了一些代码,从值中删除“继承”,这确实允许它被反序列化。
这种方法显然不好,所以我希望有一个好的方法来解决这个问题。
所以...
如果有人必须耐心阅读这篇文章并且可以提供帮助或提供建议,那将不胜感激,因为我完全没有想法。
谢谢。
最佳答案
使用 XmlAttributeOverrides 类可能会做一些事情。它主要用于特定的属性覆盖,因此它可能是也可能不是最适合您的东西。
很长的路要走,将其序列化为继承的类。然后,如果映射相同,则将 xml 反序列化为基类,然后,重新序列化为您想要的。
根据您对程序集的控制程度,您可以覆盖继承类的序列化,使其作为基类执行。
关于c# - XMLSerializer : Deserializing as derived type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8096360/