Take the 2-minute tour ×

I'm using the .NET serialization classes to XML serialize and log argument values that get passed to certain functions in my application. To this end I need a means to XML serialize the property values of any classes that get passes, but ignoring any properties that cannot be XML serialized (e.g. any Image type properties).

I could go through my classes and mark such properties with the [XmlIgnore] attribute, but ideally I'd like a serializer that just skips over such properties.

Is this achievable?

share|improve this question
add comment

4 Answers

up vote 2 down vote accepted

You could use reflection to dynamically create a XmlAttributeOverrides object to add the XmlIgnore attribute on relevant properties. You just need to implement the logic to determine whether a given type is eligible for XML serialization, and browse the object graph recursively. When you're done creating the XmlAttributeOverrides object, just pass it to the XmlSerializer constructor

share|improve this answer
add comment

This is probably about as efficient as your "XMLIgnore" idea, but you could use XPath to only pass serializeable parts to the serialize function.

share|improve this answer
add comment

If you control a common base class, you can implement this via reflection - otherwise this is likely to be a hassle. You could implement a custom Xml serialization scheme - it's not that hard, but I doubt it's worth it.

Also, if you "automatically" ignore unserializable properties for all classes, you'll need to think about the level at which you do so - otherwise previously unserializable classes become serializable themselves, but just have a few properties of their own that are not (fully) serializable.

share|improve this answer
add comment

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

Good luck!

Edit: Check Thomas' comment below. I guess he's right.

share|improve this answer
I would advice against that route : XmlSerializer doesn't directly perform the serialization, it generates another assembly to do it. So you would have to change the way the serialization assembly is generated, which could be pretty hard... –  Thomas Levesque Sep 4 '09 at 9:02
add comment

Your Answer


