views:

666

answers:

4

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?

A: 

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

Anthony
A: 

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.

Eamon Nerbonne
A: 

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.

Tor Haugen
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
+2  A: 

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

Thomas Levesque