Getting XML Serialization to Automatically Ignore Non-Serializable Properties
I am using .NET serialization classes for XML serialization and log argument values ββthat are passed to specific functions in my application. To do this, I need to XML serialize the property values ββof any classes that receive gaps, but ignoring any properties that cannot be XML serialized (like any type properties Image
).
I could loop through my classes and mark properties like this with an attribute [XmlIgnore]
, but ideally I would like the serializer to just skip such properties.
Is this achievable?
source to share
You can use reflection to dynamically create an object XmlAttributeOverrides
to add an attribute XmlIgnore
to the corresponding properties. You just need to implement logic to determine if a given type is suitable for XML serialization, and recursively look at the object graph. When you're done creating the object XmlAttributeOverrides
, just pass it to the constructorXmlSerializer
source to share
If you are in control of a common base class, you can implement this through reflection - otherwise it will probably be a problem. You can implement a custom Xml serialization scheme - it's not that hard, but I doubt it's worth it.
Also, if you "automatically" ignore non-serializable properties for all classes, you need to think about the level at which you do it - otherwise, previously unserializable classes become serializable themselves, but have only a few properties of their own, are not (fully) serializable.
source to share