C# XML Serialization – Custom Serializer or Base Class Implementing IXmlSerializable?

cnetserializationxml

I am working on a project where I have very specific xml serialization specifications, that is:

  • Some properties are elements, some are attributes

  • Some properties are required others aren't

  • Some properties are required just in some context of the overall
    object state

  • Not required properties must not be serialized

  • Properties of same type can be serialized differently

  • Some double properties should have rounding, maybe even custom
    rounding

And the list goes on…

I am currently implementing these rules using Attribute which is the only sane way.

But I wonder, what is the best way to serialize these objects? Certainly the approach that makes the most sense is to have a serializer which knows all these rules and how to handle them just as XmlSerializer, although it seems IXmlSerializable was created for this reason.

So, what would you do? Custom serializer or IXmlSerializable?

Best Answer

Using IXmlSerializable

There are some things to take into consideration when implementing this interface and you should check to see if your intended use is compatible with this. Big advantage of this approach is that you can serialize what are otherwise private or protected fields, and the fairly straightforward usage of serialization (method on the object itself). This approach might validate SRP depending on the nature of the serialized object.

Using a Serializer

Using a serializer allows you to take advantage of DI (Dependency Injection), so you can have re-usable XML serialization classes injected with DI. This makes writing tests a lot simpler as using new to create new objects makes it significantly harder to write tests(1) Disadvantage is that you have to carry around serializers to use thoughout your code and will probably need some degree of wiring code to obtain the correct serializer for a given object.

In the end, it boils down to what advantages matter more and what disadvantages would seriously hamper your development.

1) If two objects contain the same type of child object, the serialization of that object can be split off into a separate class with separate tests. The tests on the parent serializer would only need to verify the child serializers are called. Without DI you'd probably need to duplicate the tests for the children across the parents.