Skip to content

Instantly share code, notes, and snippets.

@Krummelz
Created August 29, 2013 09:33
Show Gist options
  • Save Krummelz/6376082 to your computer and use it in GitHub Desktop.
Save Krummelz/6376082 to your computer and use it in GitHub Desktop.
Courtesy of @Dominic_ZA
public static XElement Serialize(this object o)
{
XElement e = new XElement("property");
PropertyInfo[] properties;
Type _t = o.GetType();
properties = _t.GetProperties();
if (properties.Length == 0) //This implies that it is a VALUE TYPE
e.SetValue(o);
foreach (PropertyInfo p in properties)
{
Type _pT = p.PropertyType;
if (typeof(ICollection).IsAssignableFrom(_pT))
{
XElement listElem = new XElement("property");
foreach (object obj in (_t.GetProperty(p.Name).GetValue(o, null) as IEnumerable))
listElem.Add(obj.Serialize());
listElem.SetAttributeValue("ObjNameRef", p.Name); //Make a note of the proterties name
e.Add(listElem);
}
else if (_pT.Namespace != "System")
e.Add(_t.GetProperty(p.Name).GetValue(o, null).Serialize());
else
e.SetAttributeValue(p.Name, _t.GetProperty(p.Name).GetValue(o, null));
e.SetAttributeValue("ObjNameRef", p.Name); //Make a note of the proterties name
}
return e;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment