C # - hydrate an existing object using XML

I know that I can use Linq to map fields from XML to fields in a pre-existing object. Are there any features in the .NET Framework (or other libraries) that make this less convenient?

I would like to write (and HydrateFromXml will be a bit like AutoMapper):

var myObject = new MyObject(/*ctor args*/); myObject = myObject.HydrateFromXml(string xml); 

Edit:

Can I use a decorator template or a simple wrapper object here? Remove deserialization directly into the type that is wrapped in abstraction, which allows fine-grained control of the structure I need?

+7
source share
2 answers

You can use the XmlSerializer to do this:

 var serializer = new XmlSerializer(typeof(MyObject)); object result; using (TextReader reader = new StringReader(xml)) { result= serializer.Deserialize(reader); } var myObject = result as MyObject; 

In case you are already an object instance, check this question: Deserting properties into a pre-existing object

+5
source

As a quick option, you can use AutoMapper. Use XmlSerializer to deserialize to a new instance, and then use AutoMapper to map from the newly created instance to the desired instance.

+1
source

All Articles