//识别需要序列化的类型
private static readonly Type[] WriteTypes = new[] {
typeof(string), typeof(DateTime), typeof(Enum),
typeof(decimal?), typeof(Guid),typeof(int?)
};
public static bool IsSimpleType(this Type type)
{
return type.IsPrimitive || WriteTypes.Contains(type);
}
public static object ToXml(this object input)
{
return input.ToXml(null);
}
public static object ToXml(this object input, string element = "ROOT")
{
if (input == null)
return null;
if (string.IsNullOrEmpty(element))
element = "ROOT";
element = XmlConvert.EncodeName(element);
var ret = new XElement(element);
if (input != null)
{
var type = input.GetType();
if (input is IEnumerable && !type.IsSimpleType())
{
var elements = (input as IEnumerable<object>)
.Select(m => m.ToXml(element))
.ToArray();
return elements;
}
else
{
var props = type.GetProperties();
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;
}
var xx = new
{
HEADER = new { TRADEMSG = "", MACHINEID = "" },
BODY = new
{
ITEM = ITEM.Select(p => new
{
p.BRID,
p.BRXM
}).ToList(),
}
};
var aa = xx.ToXml();
引用:https://stackoverflow.com/questions/2404685/can-i-serialize-anonymous-types-as-xml