码迷,mamicode.com
首页 > 其他好文 > 详细

XML序列化

时间:2016-09-29 09:38:21      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

        /// <summary>
        /// 将指定路径XML文件序列化为指定对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="obj">需要序列化的对象</param>
        /// <param name="isOmitXmlDeclaration">true:省略XML声明;否则为false.默认false,即编写 XML 声明。</param>
        /// <param name="removeDefaultNamespace">是否移除默认名称空间(如果对象定义时指定了:XmlRoot(Namespace = "http://www.xxx.com/xsd")则需要传false值进来)</param>
        public static void XmlSerialize<T>(string path, T obj, bool isOmitXmlDeclaration = false, bool removeDefaultNamespace = true)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = isOmitXmlDeclaration;
            settings.Encoding = Encoding.UTF8;
            settings.Indent = true;
            settings.IndentChars = "\t";
            settings.NewLineOnAttributes = true;
            settings.NewLineChars = "\r\n";
            using (XmlWriter xmlwriter = XmlWriter.Create(path, settings))
            {
                XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
                if (removeDefaultNamespace)
                {
                    xmlns.Add(string.Empty, string.Empty); //在XML序列化时去除默认命名空间xmlns:xsd和xmlns:xsi
                }
                XmlSerializer ser = new XmlSerializer(typeof(T));
                ser.Serialize(xmlwriter, obj, xmlns);
            }
        }

 

XML序列化

标签:

原文地址:http://www.cnblogs.com/yuwuji/p/5918693.html

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