Question

I'm writing a simple extension that allow to serialize multi-dimensional arrays. Internally I'm using XmlSerializer for array items, but it doesn't work for read-only properties. So how can I serialize them in XML using XmlSerializer (or some another class like DataContractSerializer) without modifying classes to have these properties. I mean I have method Serialize<T>(T obj) and I would be able to serialize it for any T, even structs like KeyValuePair<T,U> with read-only properties.

Was it helpful?

Solution

This isn't possible with XmlSerializer or DataContractSerializer.

Using DataContractSerializer, you can serialize / deserialize private and even readonly fields / properties, however every field / property to serialize needs to be marked with the DataMember attribute, so it can't be used for arbitrary types, such as KeyValuePair<K,V>.

Other than doing it by hand using an XML API (such as Linq2Xml, for example) and reflection, you could look at sharpserializer which seems to do exactly what you're trying to accomplish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top