Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 303
Martin Avatar asked Feb 10 '09 11:02

Martin


People also ask

What is the correct way of using XML deserialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.

What is XmlSerializer C#?

The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors. If you use any of the constructors other than the one that takes a type then a new temporary assembly is created EVERY TIME you create a serializer, rather than only once.


2 Answers

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);
like image 189
Marc Gravell Avatar answered Sep 23 '22 16:09

Marc Gravell


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.

like image 41
Tiberiu Ana Avatar answered Sep 25 '22 16:09

Tiberiu Ana