Here is a handy method that accepts an XElement and an object. It loops through each attribute in the XML element and sets the matching property on the object:
public static object SetProperties(object obj, XElement xelement)
{
foreach (var attribute in xelement.Attributes()) //loop through attributes of element
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(attribute.Name.ToString()); //get property that matches attribute
//make sure property exists
if (propertyInfo != null)
{
if (propertyInfo.PropertyType == typeof(int) || propertyInfo.PropertyType == typeof(int?)) //int
propertyInfo.SetValue(obj, int.Parse(attribute.Value), null);
else if (propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?)) //datetime
propertyInfo.SetValue(obj, DateTime.Parse(attribute.Value), null);
else //string
propertyInfo.SetValue(obj, attribute.Value, null);
}
}
return obj;
}