标题: 如何将内存中的一个类对象实体持久化到XML文件中
- MK2 2007-06-02 22:38 阅读:307
- 评论:0 | 添加评论
最近都在研究BlogEngine.NET的代码, 在看到BlogSettings类时, 一个Singleton模式, 最特别的是它的Save()方法和Load()方法, 因为我第一次看见这种利用反射方式持久化一个对象, 所以就将它截取下来, 学习学习了, 呵呵
[图片][图片]Load()
/// <summary>
        /// Initializes the singleton instance of the <see cref="BlogSettings"/> class.
        /// </summary>
        private void Load()
        {
            //------------------------------------------------------------
            //    Local members
            //------------------------------------------------------------
            string settingsFilePath = String.Empty;
            XmlReaderSettings readerSettings;
            XmlDocument settingsDocument;
            Type settingsType;

            //------------------------------------------------------------
            //    Attempt to load configured settings
            //------------------------------------------------------------
            try
            {
                //------------------------------------------------------------
                //    Get settings location and instance type
                //------------------------------------------------------------
                settingsFilePath    = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SettingsFile"]);
                settingsType        = this.GetType();

                //------------------------------------------------------------
                //    Define XML reader settings
                //------------------------------------------------------------
                readerSettings      = new XmlReaderSettings();
                readerSettings.IgnoreComments = true;
                readerSettings.IgnoreWhitespace = true;

                //------------------------------------------------------------
                //    Load settings into XML document
                //------------------------------------------------------------
                settingsDocument    = new XmlDocument();
                using (FileStream stream = new FileStream(settingsFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (XmlReader reader = XmlReader.Create(stream, readerSettings))
                    {
                        settingsDocument.Load(reader);
                    }
                }

                //------------------------------------------------------------
                //    Enumerate through individual settings nodes
                //------------------------------------------------------------
                foreach (XmlNode settingsNode in settingsDocument.SelectSingleNode("settings").ChildNodes)
                {
                    //------------------------------------------------------------
                    //    Extract the setting's name/value pair
                    //------------------------------------------------------------
                    string name     = settingsNode.Name;
                    string value    = settingsNode.InnerText;

                    //------------------------------------------------------------
                    //    Enumerate through public properties of this instance
                    //------------------------------------------------------------
                    foreach (PropertyInfo propertyInformation in settingsType.GetProperties())
                    {
                        //------------------------------------------------------------
                        //    Determine if configured setting matches current setting based on name
                        //------------------------------------------------------------
                        if (propertyInformation.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                        {
                            //------------------------------------------------------------
                            //    Attempt to apply configured setting
                            //------------------------------------------------------------
                            try
                            {
                                propertyInformation.SetValue(this, Convert.ChangeType(value, propertyInformation.PropertyType, CultureInfo.CurrentCulture), null);
                            }
                            catch
                            {
                                // TODO: Log exception to a common logging framework?
                            }
                            break;
                        }
                    }
                }
            }
            catch
            {
                //------------------------------------------------------------
                //    Rethrow exception
                //------------------------------------------------------------
                throw;
            }
        }

Save()方法与Load很类似, 并且简单得多, 使用了Singleton模式, 使得反射的性能消耗, 只会发生在第一次初始化时:
[图片][图片]Instance
/// <summary>
        /// Gets the singleton instance of the <see cref="BlogSettings"/> class.
        /// </summary>
        /// <value>A singleton instance of the <see cref="BlogSettings"/> class.</value>
        /// <remarks></remarks>
        public static BlogSettings Instance
        {
            get
            {
                if (blogSettingsSingleton == null)
                {
                    blogSettingsSingleton = new BlogSettings();
                }
                return blogSettingsSingleton;
            }
        }

[图片][图片]Save()
/// <summary>
        /// Saves the settings to disk.
        /// </summary>
        public void Save()
        {
            //------------------------------------------------------------
            //    Local members
            //------------------------------------------------------------
            string settingsFilePath = String.Empty;
            XmlWriterSettings writerSettings;
            Type settingsType;

            //------------------------------------------------------------
            //    Attempt to persist settings
            //------------------------------------------------------------
            try
            {
                //------------------------------------------------------------
                //    Get settings storage path and instance type
                //------------------------------------------------------------
                settingsFilePath        = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SettingsFile"]);
                settingsType            = this.GetType();

                //------------------------------------------------------------
                //    Define XML writer settings used to generate output
                //------------------------------------------------------------
                writerSettings          = new XmlWriterSettings();
                writerSettings.Indent   = true;

                //------------------------------------------------------------
                //    Create XML writer against file path
                //------------------------------------------------------------
                using (XmlWriter writer = XmlWriter.Create(settingsFilePath, writerSettings))
                {
                    //------------------------------------------------------------
                    //    Write settings root element
                    //------------------------------------------------------------
                    writer.WriteStartElement("settings");

                    //------------------------------------------------------------
                    //    Enumerate through settings properties
                    //------------------------------------------------------------
                    foreach (PropertyInfo propertyInformation in settingsType.GetProperties())
                    {
                        //------------------------------------------------------------
                        //    Attempt to write settings name/value pairs
                        //------------------------------------------------------------
                        try
                        {
                            //------------------------------------------------------------
                            //    Verify not 
                            //------------------------------------------------------------
                            if (propertyInformation.Name != "Instance")
                            {
                                //------------------------------------------------------------
                                //    Extract property value and its string representation
                                //------------------------------------------------------------
                                object propertyValue    = propertyInformation.GetValue(this, null);
                                string valueAsString    = propertyValue.ToString();

                                //------------------------------------------------------------
                                //    Format null/default property values as empty strings
                                //------------------------------------------------------------
                                if (propertyValue.Equals(null))
                                {
                                    valueAsString   = String.Empty;
                                }
                                if (propertyValue.Equals(Int32.MinValue))
                                {
                                    valueAsString   = String.Empty;
                                }
                                if (propertyValue.Equals(Single.MinValue))
                                {
                                    valueAsString   = String.Empty;
                                }

   &n
添加评论
返回顶部 | 返回首页