代码之家  ›  专栏  ›  技术社区  ›  Jeremy Holovacs

自定义配置部分-KISS方法

  •  0
  • Jeremy Holovacs  · 技术社区  · 13 年前

    我有一个app.config节,我想定义为 IDictionary<string, IDictionary<string, string>> 在app.config文件中看起来像这样:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <section name="ServiceInstances" type="MyProject.Configuration, MyProject"/>
        </configSections>
        <ServiceInstances>
            <ServiceInstance name="service1">
                <kvp key="key1" value="value1"/>
                <kvp key="key2" value="value2"/>
            </ServiceInstance>
            <ServiceInstance name="service2">
                <kvp key="key3" value="value3"/>
                <kvp key="key2" value="value2"/>
            </ServiceInstance>
        </ServiceInstances>
    </configuration>
    

    我看到的所有教程似乎都深入到了这一点,我只是在寻找一种快速而肮脏的方法来做到这一点:

    IDictionary<string, string> foo = Configuration.GetDictionary("service1");
    IDictionary<string, string> bar = Configuration.GetDictionary("service2");
    

    看起来这应该是几行代码,但教程似乎不必要地使其复杂化了。对此有一个快速的答案吗?如果有,有人能告诉我它应该是什么样子吗?

    2 回复  |  直到 13 年前
        1
  •  2
  •   Jan    13 年前

    首先将XML文件解析为 Dictionary<string, Dictionary<string, string>> 。看起来是这样的:

    public Dictionary<string, Dictionary<string, string>> getDictionary()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(@"path/to/file.xml");
    
        Dictionary<string, Dictionary<string, string>> outer = new Dictionary<string, Dictionary<string, string>>();
        Dictionary<string, string> inner;
    
        //cycle through outer nodes
        foreach (XmlNode service in doc.SelectNodes("/configuration/ServiceInstances/ServiceInstance"))
        {
            inner = new Dictionary<string, string>();
            //cycle through inner nodes
            foreach (XmlNode kvp in service.SelectNodes("kvp"))
            {
                inner.Add(kvp.Attributes["key"].Value, kvp.Attributes["value"].Value);
            }
            outer.Add(service.Attributes["name"].Value, inner);
        }
    
        return outer;
    }
    

    然后你可以这样称呼你的字典:

    var foo = getDictionary();
    Dictionary<string,string> bar = foo["service1"];
    
        2
  •  1
  •   Giedrius    13 年前

    您可以使用配置节设计器来完成以下脏工作:

    http://csd.codeplex.com/

    它有visual studio设计器支持,生成示例配置,只是到目前为止有一个问题-如果是VS2012,需要安装VS2010,但我认为很快就会解决。