你应该考虑使用配置元素集合 http://msdn.microsoft.com/en-us/library/system.configuration.configurationelementcollection.aspx and 键值配置集合 http://msdn.microsoft.com/en-us/library/system.configuration.keyvalueconfigurationcollection.aspx对于要用作集合的元素。在这种情况下,您必须创建一个元素集合,每个元素都有一个 KeyValueConfigurationCollection。因此,您将拥有类似以下的内容,而不是上面的 XML 配置:
<providers>
<provider key="products">
<queries>
<add key="whatever" value="stuff" />
...etc...
<queries>
<provider>
</providers>
您可以为每个“提供者”重复使用“查询”元素,该元素将是您的 KeyValueConfigurationCollection。
快速谷歌搜索得到了结果MSDN 上的这篇文章 http://msdn.microsoft.com/en-us/library/2tw134k3.aspx,这也可能有帮助。
编辑 - 代码示例
您的根部分定义将如下所示:
public class ProviderConfiguration : ConfigurationSection
{
[ConfigurationProperty("Providers",IsRequired = true)]
public ProviderElementCollection Providers
{
get{ return (ProviderElementCollection)this["Providers"]; }
set{ this["Providers"] = value; }
}
}
然后,您的 Providers ElementCollection:
public class ProviderCollection : ConfigurationElementCollection
{
public ProviderElement this[object elementKey]
{
get { return BaseGet(elementKey); }
}
public void Add(ProviderElement provider)
{
base.BaseAdd(provider);
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
protected override ConfigurationElement CreateNewElement()
{
return new ProviderElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ProviderElement)element).Key;
}
protected override string ElementName
{
get { return "Provider"; }
}
}
然后,您的 Provider 元素:
public class Provider : ConfigurationElement
{
[ConfigurationProperty("Key",IsRequired = true, IsKey = true)]
public string Key
{
get { return (string) this["Key"]; }
set { this["Key"] = value; }
}
[ConfigurationProperty("Queries", IsRequired = true)]
public KeyValueConfigurationCollection Queries
{
get { return (KeyValueConfigurationCollection)this["Queries"]; }
set { this["Queries"] = value; }
}
}
您可能需要对 KeyValueConfigurationCollection 进行一些修改才能使其正常工作,但我认为这是总体思路。然后,当在代码中访问这些内容时,您将执行以下操作:
var myConfig = (ProviderConfiguration)ConfigurationManager.GetSection("Providers");
//and to access a single value from, say, your products collection...
var myValue = myConfig.Providers["Products"].Queries["KeyForKeyValuePairing"].Value;
希望有帮助。现在别让我把它翻译成 VB :-D