views:

572

answers:

2

Is there a clever way of adding XML serialization instructions without modifying the serialized class?

I don’t like the default serialization and I can’t modify the class. I was considering inheriting the class, and using Shadows (VB.NET) to re-implement the properties (with the serialization instructions), but it results in a lot of duplicate code and just looks terrible.

The ideal solution I'm looking for is basically a method to keep all the serialization instructions in a separate file.

+1  A: 

Use reflection to get the values of all the properties from the class then write them as attributes on to an XmlNode

PropertyInfo[] properties = control.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
  object o = property.GetValue(control, null);
  // write value of o.ToString() out as an attribute on a XmlNode
  // where attribute name is property.Name
}
benPearce
Wouldn't that be almost the same as hand-coding, i.e. not using .NET XmlSerialization? The point is I just want to tinker a bit with the way the xml is created, applying different names and force the serializer to create attributes rather than elements for some properties.
Jakob Gade
There is some more information here http://stackoverflow.com/questions/123540/modifying-existing-net-assembles, otherwise inheritance is your only option. My suggestion means that if an new attribute is added to the class you do not need to modify any code to serialize it.
benPearce
+3  A: 

Have you looked into using XmlAttributeOverrides?

.NET Framework Class Library: XmlAttributeOverrides Class

first, you can control and augment the serialization of objects found in a DLL--even if you do not have access to the source;

second, you can create one set of serializable classes, but serialize the objects in multiple ways. For example, instead of serializing members of a class instance as XML elements, you can serialize them as XML attributes, resulting in a more efficient document to transport.

hurst
Brilliant. That was exactly what I was looking for. Thanks! :)
Jakob Gade