C# 对象转XML 支持匿名类
程序员文章站
2022-06-18 09:34:10
在网上找了很多关于对象转XML的,大多不支持匿名类转换,今天在*找了一篇文章 但是有些许BUG 已经修复 调用: 记得引入命名空间 ......
在网上找了很多关于对象转xml的,大多不支持匿名类转换,今天在*找了一篇文章 但是有些许bug 已经修复
1 public static class objecttoxml 2 { 3 private static readonly type[] writetypes = new[] { 4 typeof(string), typeof(datetime),typeof(decimal), typeof(guid), 5 }; 6 public static bool issimpletype(this type type) 7 { 8 return type.isprimitive || writetypes.contains(type) || type.isenum; 9 } 10 public static xelement toxml(this object input) 11 { 12 return input.toxml(null); 13 } 14 15 private static string getxmlelementattributename(propertyinfo info) 16 { 17 string attributename = ""; 18 19 var attr = info.getcustomattributes(true); 20 if (attr != null && attr.length > 0) 21 { 22 23 foreach (var item in attr) 24 { 25 if (item is xmlelementattribute) 26 { 27 var temp = item as xmlelementattribute; 28 attributename = temp.elementname; 29 30 31 } 32 else if(item is xmlrootattribute) 33 { 34 var temp = item as xmlrootattribute; 35 attributename = temp.elementname; 36 } 37 } 38 } 39 return attributename; 40 } 41 42 private static object getpropertyvalue(object input, propertyinfo info) 43 { 44 if (info.propertytype.isenum) 45 { 46 return (int)info.getvalue(input); 47 } 48 return info.getvalue(input); 49 } 50 51 public static xelement toxml(this object input, string element) 52 { 53 if (input == null) 54 return null; 55 56 if (string.isnullorempty(element)) 57 element = "object"; 58 59 element = xmlconvert.encodename(element); 60 var ret = new xelement(element); 61 62 if (input != null) 63 { 64 var type = input.gettype(); 65 var props = type.getproperties(); 66 var elements = from prop in props 67 let name = xmlconvert.encodename(getxmlelementattributename(prop) == "" ? prop.name : getxmlelementattributename(prop)) 68 let val = getpropertyvalue(input,prop) 69 let value = prop.propertytype.issimpletype() 70 ? new xelement(name, val) 71 : val.toxml(name) 72 where value != null 73 select value; 74 75 ret.add(elements); 76 } 77 78 return ret; 79 } 80 }
调用:
var model = new { name = "张三", age = 18 }; model.toxml("requestparameter").tostring();
记得引入命名空间