C# - Hydrate existing object with XML
c#, xml
Solution
You can use `XmlSerializer` to do that:
var serializer = new XmlSerializer(typeof(MyObject));
object result;
using (TextReader reader = new StringReader(xml))
{
result= serializer.Deserialize(reader);
}
var myObject = result as MyObject;
For a situation when you're object instance already exists check this question: Deserializing properties into a pre-existing object
Problem
I know I can use Linq to map fields from XML to fields in a pre-existing object. Are there any functions in the .NET Framework (or other libraries) that make this less manual. I would like to write (and have the HydrateFromXml behave a little like AutoMapper does): ``` var myObject = new MyObject(/*ctor args*/); myObject = myObject.HydrateFromXml(string xml); ``` Edit: Could I use the decorator pattern or a simple wrapper object here? Deserialize directly into a type that is wrapped by an abstraction that permits the fine-grained construction control I need?