首页 > 学院 > 开发设计 > 正文

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

2019-11-14 13:58:42
字体:
来源:转载
供稿:网友

序列化实体类成为一个干净的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;        }

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表