【发布时间】:2018-10-05 05:28:59
【问题描述】:
考虑以下配置部分:
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="xxx.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</sectionGroup>
</configSections>
<applicationSettings>
<xxx.Properties.Settings>
<setting name="xxx_Service1" serializeAs="String">
<value>https://xxx.service1</value>
</setting>
<setting name="xxx_Service1" serializeAs="String">
<value>https://xxx.service2</value>
</setting>
<setting name="xxx_Service1" serializeAs="String">
<value>https://xxx.service3</value>
</setting>
</xxx.Properties.Settings>
</applicationSettings>
我尝试实现 System.Configuration.ClientSettingsSection 的自定义版本。我需要完全相同的层次结构
ConfigSection
- ConfigElement
- ConfigElement
- ConfigElement
基于AssemblyExplorer的代码我编写了自定义实现:
{
static void Main()
{
var sec = (CustomClientSettingsSection) ConfigurationManager.GetSection("serviceSettings");
Console.Read();
}
}
public class CustomClientSettingsSection : ConfigurationSection
{
private static readonly ConfigurationProperty _propSettings = new ConfigurationProperty((string)null,
typeof(CustomSettingElementCollection), (object)null, ConfigurationPropertyOptions.IsDefaultCollection);
[ConfigurationProperty("", IsDefaultCollection = true)]
public CustomSettingElementCollection Services
{
get { return (CustomSettingElementCollection)this[CustomClientSettingsSection._propSettings]; }
}
}
public class CustomSettingElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new CustomSettingElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((CustomSettingElement)element).Key;
}
}
public class CustomSettingElement : ConfigurationElement
{
private static readonly ConfigurationProperty _propName = new ConfigurationProperty("name", typeof(string), (object)"", ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey);
internal string Key
{
get
{
return this.Name;
}
}
[ConfigurationProperty("name", DefaultValue = "", IsKey = true, IsRequired = true)]
public string Name
{
get
{
return (string)this[CustomSettingElement._propName];
}
set
{
this[CustomSettingElement._propName] = (object)value;
}
}
}
我正在尝试解析这个 config.xml
<configSections>
<section name="serviceSettings" type="ConsoleApplication1.CustomClientSettingsSection, ConsoleApplication1"/>
</configSections>
<serviceSettings>
<setting name="xxx_Service1">
</setting>
<setting name="xxx_Service2">
</setting>
</serviceSettings>
我得到错误:
无法识别的元素“设置”。
如何解析此配置并获取具有相同属性的configElement 列表?
【问题讨论】:
-
我建议使用 XmlDocument 和 .GetElementsByTagName("setter")
-
我在配置文件中使用自定义配置,我必须使用 ConfigurationManager 阅读
-
我建议改用 .NET Core 引入的新配置类。这些包符合 .NET 标准,这意味着它们也可以被完整的框架项目使用。您不需要 任何 代码来定义部分并将设置解析为对象。