如何读取XML数据库中的一个配置节? [英] How to Read a Configuration Section from XML in a Database?

查看:168
本文介绍了如何读取XML数据库中的一个配置节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的配置类:

public class MyConfig : ConfigurationSection
{
        [ConfigurationProperty("MyProperty", IsRequired = true)]
        public string MyProperty
        {
            get { return (string)this["MyProperty"]; }
            set { this["MyProperty"] = value; }
        }
}

和它被实例化另一个类像这样

And it is being instantiated by another class like this

(MyConfig)ConfigurationManager.GetSection("myConfig")

我们正在做一些改变,现在存储在数据库中的配置文件作为一个XML,酷似它是目前在配置文件中。

We are making some changes and are now storing the configuration file in the DB as an xml, exactly like it is currently in the config file.

我想保持MyConfig作为一个配置节向后兼容,但仍然能够通过使用从数据库中检索XML字符串来实例化。

I would like to maintain the MyConfig as a ConfigurationSection for backwards compatibility but still be able to instantiate it by using the XML string retrieved from the DB.

这可能吗?如果是这样,怎么样? (请记住,它应该仍然工作作为实例以上)

Is it possible? If so, how? (Keep in mind it should still work as instantiated above)

推荐答案

我的建议是保持当前的MyConfig类,但是从数据库加载XML在构造函数,然后在MyConfig的每个属性,你可以把逻辑判断,你得到(数据库或config文件)的值,如果你需要从任一位置上拉配置,或者将其退回,如果该值是空的。

My suggestion would be to keep your current MyConfig class but load your XML from your database in the constructor, then in each property of your MyConfig, you can put in logic to determine where you get the value from (either database or .config file) if you need to pull config from either location, or have it fall back if the value is empty.

public class MyConfig : ConfigurationSection
{
    public MyConfig()
    {
        // throw some code in here to retrieve your XML from your database
        // deserialize your XML and store it 
        _myProperty = "<deserialized value from db>";
    }

    private string _myProperty = string.Empty;

    [ConfigurationProperty("MyProperty", IsRequired = true)]
    public string MyProperty
    {
        get
        {
            if (_myProperty != null && _myProperty.Length > 0)
                return _myProperty;
            else
                return (string)this["MyProperty"];
        }
        set { this["MyProperty"] = value; }
    }
}

这篇关于如何读取XML数据库中的一个配置节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆