Ответ 1
Чтобы ваши элементы коллекции сидели непосредственно в родительском элементе (а не в элементе дочерней коллекции), вам нужно переопределить свой ConfigurationProperty
. Например, предположим, что у меня есть элемент коллекции, например:
public class TestConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
}
}
И коллекция, например:
[ConfigurationCollection(typeof(TestConfigurationElement), AddItemName = "test")]
public class TestConfigurationElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new TestConfigurationElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((TestConfigurationElement)element).Name;
}
}
Мне нужно определить родительский раздел/элемент как:
public class TestConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("", IsDefaultCollection = true)]
public TestConfigurationElementCollection Tests
{
get { return (TestConfigurationElementCollection)this[""]; }
}
}
Обратите внимание на атрибут [ConfigurationProperty("", IsDefaultCollection = true)]
. Давая ему пустое имя, и установка его как коллекции по умолчанию позволяет мне определить мою конфигурацию, например:
<testConfig>
<test name="One" />
<test name="Two" />
</testConfig>
Вместо:
<testConfig>
<tests>
<test name="One" />
<test name="Two" />
</tests>
</testConfig>