在网上找了很多关于对象转XML的,大多不支持匿名类转换,今天在stackoverflow找了一篇文章  但是有些许BUG  已经修复

 public static class ObjectToXML
{
private static readonly Type[] WriteTypes = new[] {
typeof(string), typeof(DateTime),typeof(decimal), typeof(Guid),
};
public static bool IsSimpleType(this Type type)
{
return type.IsPrimitive || WriteTypes.Contains(type) || type.IsEnum;
}
public static XElement ToXml(this object input)
{
return input.ToXml(null);
} private static string GetXMLElementAttributeName(PropertyInfo info)
{
string attributeName = ""; var attr = info.GetCustomAttributes(true);
if (attr != null && attr.Length > )
{ foreach (var item in attr)
{
if (item is XmlElementAttribute)
{
var temp = item as XmlElementAttribute;
attributeName = temp.ElementName; }
else if(item is XmlRootAttribute)
{
var temp = item as XmlRootAttribute;
attributeName = temp.ElementName;
}
}
}
return attributeName;
} private static object GetPropertyValue(object input, PropertyInfo info)
{
if (info.PropertyType.IsEnum)
{
return (int)info.GetValue(input);
}
return info.GetValue(input);
} 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();
var elements = from prop in props
let name = XmlConvert.EncodeName(GetXMLElementAttributeName(prop) == "" ? prop.Name : GetXMLElementAttributeName(prop))
let val = GetPropertyValue(input,prop)
let value = prop.PropertyType.IsSimpleType()
? new XElement(name, val)
: val.ToXml(name)
where value != null
select value; ret.Add(elements);
} return ret;
}
}

调用:

var model = new {
Name = "张三",
Age =
}; model.ToXml("RequestParameter").ToString();

记得引入命名空间

04-28 01:44