Skip to content

Instantly share code, notes, and snippets.

@johncoder
Created October 7, 2011 17:21
Show Gist options
  • Save johncoder/1270843 to your computer and use it in GitHub Desktop.
Save johncoder/1270843 to your computer and use it in GitHub Desktop.
inflate type from xml
public T Inflate<T>() where T : class
{
var attr = typeof(T)
.GetCustomAttributes(true)
.OfType<XmlRootAttribute>()
.SingleOrDefault();
string root;
// Use ElementName if it's provided, otherwise use name of the type
// because Linq to Xml will use this name to find the root node
if (attr != null)
root = attr.ElementName;
else
root = typeof(T).Name;
XmlSerializer xml = new XmlSerializer(typeof(T));
var doc = XDocument.Load(new XmlNodeReader(ResponseXml));
var element = doc.Descendants(root).SingleOrDefault();
T obj = null;
using (var reader = element.CreateReader())
{
obj = (T)xml.Deserialize(reader);
}
// Some properties are ignored because they're just the Xml Content
// Find those properties and set the content.
SetXmlContentMembers<T>(element, obj);
return obj;
}
private void SetXmlContentMembers<T>(XElement element, T obj) where T : class
{
// Process the XmlContentAttribute properties
var props = typeof(T).GetProperties()
.Where(prop => prop.GetCustomAttributes(true).OfType<XmlContentAttribute>().Any());
// just return if no XmlContent properties were found
if (!props.Any()) return;
// get a list of properties and their XmlContent attributes
var propertiesAndNames = from prop in props
let attr = prop.GetCustomAttributes(true).OfType<XmlContentAttribute>().FirstOrDefault()
select new
{
Attribute = attr,
Property = prop
};
foreach (var pair in propertiesAndNames)
{
string elementName = string.Empty;
// Use the ElementName on the attribute, default to property name
if (pair.Attribute != null && !string.IsNullOrEmpty(pair.Attribute.ElementName))
elementName = pair.Attribute.ElementName;
else
elementName = pair.Property.Name;
// use Linq to Xml to find the element by name
var value = element.Descendants(elementName).FirstOrDefault();
// if the element was found, set the contents!
if (value != null)
{
pair.Property.SetValue(obj, value.ToString(), null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment