Compatibility with XmlSerializer xsi:type attribute
See original GitHub issueHi,
My project currently relies on XmlSerializer to load/save a tree of model objects. All the model classes inherit from a base class (imaginatively named Entity), and the root object is of type Project. For reasons now long forgotten, Entity is decorated with an XmlTypeAttribute mapping it to the ModelObject element, which causes XmlSerializer to record the actual type in an xsi:type attribute (XML example below).
Ideally I would like to transition to ExtendedXmlSerializer while maintaining full backwards compatibility with the current XML. The graph is straightforward (XmlSerializer could handle it… 😃 ) and I am really only looking for migrations support. Maybe it will be necessary to break backwards compatibility and process the existing files with XSLT before feeding them to ExtendedXmlSerializer, but it would be super nice just to keep the exact same XML structure…
My question is: is there is a way to get ExtendedXmlSerializer to observe the xsi:type attributes when deserialising? At the moment configuration fails as there are 103 types that all inherit from Entity and hence map to the ModelObject element…
[Serializable]
[XmlType("ModelObject")]
class Entity
{
List<Entity> Children { get; }
}
[Serializable]
class Project : Entity
{
// Some project-specific stuff
}
[Serializable]
class AnotherModelClass : Entity
{
// Some other stuff
}
The XML files from XmlSerializer look like this:
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Children>
<ModelObject xsi:type="AnotherModelClass">
<Children>
</Children>
<!-- some other stuff -->
</ModelObject>
</Children>
<!-- project-related stuff -->
</Project>
My config looks like this, where serializableTypes
is a list of the 100-odd types derived from Entity, obtained at runtime using Reflection. (Color, Vector, Vector3D, and TimeSpan are the only types in the graph which are not derived from Entity and not natively supported by XmlSerializer.)
var extendedXmlSerializer = new ConfigurationContainer()
.CustomSerializer<Color, ColorSerializer>()
.CustomSerializer<Vector, VectorSerializer>()
.CustomSerializer<Vector3D, Vector3DSerializer>()
.CustomSerializer<TimeSpan, TimeSpanSerializer>()
.EnableImplicitTyping(serializableTypes)
.Create();
Issue Analytics
- State:
- Created 4 years ago
- Comments:8 (6 by maintainers)
Top GitHub Comments
OK, that appears to work! Now it is descending through the tree correctly, but something is causing the deserialisation to terminate early. …I have some tracing to do to find out where this is happening, and if it is related to this issue.
Thanks again!
The code committed earlier here has been pushed out to the public NuGet. Please let us know if you have any further issues/questions around this and we’ll do our best to help you out. Closing for now.