码迷,mamicode.com
首页 > Windows程序 > 详细

C#序列化s实体类成Xml,去除空格、换行符以及命名空间

时间:2015-09-25 13:09:34      阅读:454      评论:0      收藏:0      [点我收藏+]

标签:

序列化实体类成为一个干净的Xml,不带空格、换行符以及命名空间

        /// <summary>
        /// 序列化成XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize<T>(T obj, Encoding encoding)
        {
            string result = string.Empty;
            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                    //序列化对象
                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    namespaces.Add("", "");

                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, encoding);

                    xmlTextWriter.Formatting = System.Xml.Formatting.None;
                    xmlSerializer.Serialize(xmlTextWriter, obj, namespaces);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();

                    result = encoding.GetString(memoryStream.ToArray());
                }
            }
            catch
            {
                
            }
            return result;
        }

 

C#序列化s实体类成Xml,去除空格、换行符以及命名空间

标签:

原文地址:http://www.cnblogs.com/crazybottle/p/4837658.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!