1
votes

I have a funky scenario that, thanks to our use of .NET 4 and C# 4, seemed to be in the bag. As it turns out, the solution is more complex, and possibly non-existent outside of some completely custom solution.

In a nutshell, I need to serialize a dynamic object that has a set of fixed, required properties, and an arbitrary set of optional properties. The root element must include a custom xml namespace in the xmlns attribute, and it may be necessary for some of the child objects to use different xml namespaces. Our first approach was to derive a custom class from DynamicObject. This allowed us to add an XmlRootAttribute and specify a namespace. Barring the complication of defining custom namespaces on dynamic properties, even this simple approach did not seem to work. The XmlSerializer, despite being passed a dynamic variable as the object to serialize, simply serializes the hard-coded properties, and ignores any dynamic aspects of the object.

We have been using JsonFx 2.0 for a while, and decided to give that a try. With some careful improvements to our DynamicObject derivative, we were able to get JsonFx 2.0 to serialize all of the necessary content, however it refuses to serialize any xmlns attributes.

Is there some way to serialize a partially dynamic object to xml and include specific namespaces? Or is this simply a case of having to define an arbitrarily complex object graph, choosing the graph that fits the specific needs as dynamically derived at runtime?

Seems the xml serialization story for .NET 4 is rather lax when it comes to serializing dynamic objects.

1
Have you figured out a different solution to this problem? If so, it would be nice if you posted it here. :-)Asbjørn Ulsberg

1 Answers

2
votes

The XmlSerializer will poke at your IXmlSerializable implementation (if you implement it) before doing any of the reflection magic it needs to find [XmlElement] and its crazy siblings. Just implement IXmlSerializable alongside DynamicObject and you should be able to dynamically both read and write whatever XML you please.