Serializes anonymous objects to xml
Code was originally created by Matthew Whited. http://stackoverflow.com/questions/2404685/can-i-serialize-anonymous-types-as-xml/2404984#2404984 I just added the support for enumerable types.
Example:
var myObj = new
{
Name = "coco",
Desc = "hehe",
Created = DateTime.Now,
Age = 123456,
MyCars = new List<string>()
{
"aaa",
"bbb",
"ccc"
},
Ages = new List<int>()
{
123, 82718, 1221
},
ArrayAges = new int[]
{
12,13,41
},
Properties = new List<DateTime>()
{
DateTime.Now.AddMonths(-1),
DateTime.Now.AddMonths(-2),
DateTime.Now.AddMonths(-3),
},
};
Console.WriteLine(myObj.ToXml("MyObject"));
The code:
public static class Tools
{
private static readonly Type[] WriteTypes = new[] {
typeof(string), typeof(DateTime), typeof(Enum),
typeof(decimal), typeof(Guid),
};
public static bool IsSimpleType(this Type type)
{
return type.IsPrimitive || WriteTypes.Contains(type);
}
public static bool IsEnumerable(this Type type)
{
return (type.GetInterface("IEnumerable") != null);
}
public static XElement ToXml(this object input)
{
return input.ToXml(null);
}
public static XElement ToXml(this object input, string element)
{
if (input == null)
return null;
if (string.IsNullOrEmpty(element))
element = "object";
element = XmlConvert.EncodeName(element);
var ret = new XElement(element);
if (input != null)
{
var type = input.GetType();
var props = type.GetProperties();
if (!type.IsSimpleType() && type.IsEnumerable())
{
// singularize the element name
if (element.EndsWith("ies"))
element = element.Substring(0, element.Length-3) + "y";
else if (element.EndsWith("s") && element.Length > 1)
element = element.Substring(0, element.Length-1);
foreach (object item in input as IEnumerable)
{
ret.Add(item.GetType().IsSimpleType()
? new XElement(element, item)
: item.ToXml(element));
}
}
else
{
var elements = from prop in props
let name = XmlConvert.EncodeName(prop.Name)
let val = prop.GetValue(input, null)
let value = prop.PropertyType.IsSimpleType()
? new XElement(name, val)
: val.ToXml(name)
where value != null
select value;
ret.Add(elements);
}
}
return ret;
}
}
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


983
0




Mark 'c#' tag as 'like'
Mark 'c#' tag as 'ignore'