C#序列化匿名对象为XML

来源:互联网 发布:土耳其软糖淘宝 编辑:程序博客网 时间:2024/06/04 23:19

封装xml序列化类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;using System.Xml.Linq;namespace Xml.Utils{    /// <summary>    /// 匿名对象序列化为XML    /// </summary>    public static class XmlTools    {        //识别需要序列化的类型        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 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();                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 entityuser = (from u in db.User                              where u.username == username                              select new                              {                                  id = u.id,                                  username = u.username,                                  email = u.email,                              }).FirstOrDefault();


测试序列化匿名对象
entityuser.ToXml(); //使用方法,生成默认根节点名称xml
entityuser.ToXml("user"); //生成自定义根节点名称xml

0 0
原创粉丝点击