Martin Martin - 26 days ago 16
C# Question

How to use XmlSerializer to deserialize into an existing instance?

Is it somehow possible to use the XmlSerializer to deserialize its data into an existing instance of a class rather than into a new one?

This would be helpful in two cases:


  1. Easily merge two XML files into one object instance.

  2. Let object constructer itself be the one who is loading its data from the XML file.



If the is not possible by default it should work by using reflection (copying each property after the deserialisation) but this would be an ugly solution.

Answer

I think you're on the right track with the Reflection idea.

Since you probably have a wrapper around the XML operations anyway, you could take in the destination object, do the deserialization normally into a new object, then do something similar to cloning by copying over one by one only the properties holding non-default values.

It shouldn't be that complex to implement this, and it would look to consumers from the rest of your application just like in-place deserialization.

Comments