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.

Jakob Gade
  • 12,319
  • 15
  • 70
  • 118

2 Answers2

3

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
  • 1,710
  • 12
  • 8
0

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
  • 37,735
  • 14
  • 62
  • 96
  • 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 Oct 18 '08 at 06:42
  • 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 Oct 18 '08 at 20:55