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?

+2


source to share


4 answers


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



+2


source


This is probably as efficient as your XMLIgnore idea, but you can only use XPath to pass the serializable parts to the serialization function.



0


source


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.

0


source


You must subclass the XmlSerializer and override the virtual protected method Serialize (object, XmlSerializationWriter). You will probably need to implement your own XmlSerializationWriter.

Good luck!

Edit: Read Thomas's comment below. I think he's right.

0


source







All Articles