I’m working on a project right now where I have an XML data source that is provided by a third party and I need to import the data into a usable object model which I plan to store in MongoDB.
I didn’t want to have to write a ton of redundant code for each and every field on the object in a factory pattern. There is literally about 40 to 50 fields on this object.
What I discovered is this cool thing called reflection.
Here is the code snippet:
var name = "PropertyName";
var newValue = "This is my value I want to set";
PropertyInfo prop = obj.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (null != prop && prop.CanWrite)
{
prop.SetValue(obj, Convert.ChangeType(newValue, prop.PropertyType), null);
}
Essentially the first two lines here are ensuring that firstly the property exists on the object and secondly that the property is settable.
Since all the properties on my object match up to fields on my datasource, at least the fields I want to translate over do, this works great.
Here is the method I wrote that allows me to pass an XElement with a Generic and iteratively populate all the fields of the object from values nested within the XElement.
private static T BuildByReflection<T>(XElement element) where T : new()
{
var obj = new T();
foreach (var subElem in element.Elements())
{
var name = subElem.Name.LocalName;
PropertyInfo prop = obj.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (null != prop && prop.CanWrite)
{
prop.SetValue(obj, Convert.ChangeType(subElem.Value, prop.PropertyType), null);
}
}
return obj;
}