views:

699

answers:

3

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.

+2  A: 

Basically, you can't. XmlSerializer is strictly constructive. The only interesting thing you can do to customize XmlSerializer is to implement IXmlSerializable and do everything yourself - not an attractive option (and it will still create new instances with the default constructor, etc).

Is xml a strict requirement? If you can use a different format, protobuf-net supports merging fragments into existing instances, as simply as:

Serializer.Merge(source, obj);
Marc Gravell
+1  A: 

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.

Tiberiu Ana
A: 

I hit the same problem a few weeks ago.

I put a method Deserialize(string serialized form) in the ISelfSerializable interface that an entity class of mine implemented. I also made sure the interface forced the class to have a default constructor.

In my factory I created an object of that type and then deserialized the string into it.

Andrei Rinea