How to use XmlSerializer to deserialize into an existing instance?

Is it possible to somehow use the XmlSerializer to deserialize my data into an existing instance of the class, and not into a new one?

This would be useful in two cases:

  • It is easy to combine two XML files into one instance of an object.
  • Let the constructor object itself be the one who loads its data from the XML file.

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

+6
c # serialization
source share
4 answers

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

Since you probably have a wrapper around the XML operations, you can take the target object, usually deserialize to a new object, and then do something like cloning, copying only the properties, the default values, one after the other.

It should not be so difficult to implement this, and it will look for consumers from the rest of your application, as well as in-place deserialization.

+1
source share

Basically, you cannot. XmlSerializer is strictly constructive. The only interesting thing you can do to configure XmlSerializer is to implement IXmlSerializable and do it all yourself is not an attractive option (and it will still create new instances with a standard constructor, etc.).

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

 Serializer.Merge(source, obj); 
+4
source share

I ran into the same problem a few weeks ago.

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

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

0
source share

This is not a thread safe thing ... But you can do:

 [Serializable] public class c_Settings { static c_Settings Default; public static SetExistingObject(c_Settings def) { Default = def; } public string Prop1; public bool Prop2; public c_Settings() { if (Default == null) return; MemberInfo[] members = FormatterServices.GetSerializableMembers(typeof(c_Settings)); FormatterServices.PopulateObjectMembers(this, members, FormatterServices.GetObjectData(Default, members)); } } 

Thus, you pass your object to the deserializer and deserializer, only overwrites everything that is written in .xml.

0
source share

All Articles