Xml serialization, how to exclude objects at runtime-Collection of common programming errors

Hello,

This is just an idea, theory if you like, that might be a solution but I haven’t put this into practise so it may not work. The way you control whether an object is serialised is through attributes, the XmlIgnore attribute, however the problem, as you may already know, is you cannot base that attribute on the value of a variable. The attribute doesn’t accept a true / false value and even if it did it wouldn’t work off the value of a variable. There are attributes that do allow you to use the value of a variable (DebuggerDisplayAttribute allows it), so maybe one idea could be to develop a custom XmlIgnore attribute, maybe that would work.

The idea I had though was to provide a set of XmlAttributeOverrides to the serialiser. This object allows you to change the attributes specified in the class being serialised, so for example you can remove a XmlIgnore attribute with a XmlElement attribute or, more importantly, vice versa. Maybe this is the solution, you could base what attributes are overriden based on the value of CanSerialise, so for example by default the object being serialised has an attribute of XmlElement, somewhere in your code you check the value of CanSerialise and if false you override the XmlElement with an XmlIgnore element and hence it doesn’t get serialised.

Thats just an idea off the top of my head so maybe someone has an easier solution, or even some code that demonstrates using the XmlAttributeOverrides class. Anyway I hope this helps and at least gives you a couple of approaches to achieving whats needed.