I'm writing a small C# application that needs to be able to read/write some config data as XML. I'm doing this by creating some simple model classes with properties that have XmlElement
attributes where needed, and running the whole thing through an XmlSerializer
.
I would like to have the XmlSerializer
behave exactly as it usually does, except I want any null properties on serialized objects to be written as empty elements. (Currently it skips them entirely.) And likewise, when deserializing, I'd like it to interpret empty elements as null, rather than as an empty string.
What's the most straight-forward way to achieve this? The suggestions I've seen for similar situations involve using the IsNullable
argument for XmlElement
, creating ShouldSerialize
methods, etc. This has to be done for every property, creating a lot of unnecessary code. In this case, I want it to be universal for anything I'm (de)serializing. If I need to extend XmlSerializer
, that's fine, and I could live with implementing IXmlSerializable
on the model classes, but I'm not entirely sure where to start with those two possible approaches.