自定义配置部分的配置文件中存在未识别的元素“Item”

12

我有一个基于某些类的自定义配置。我的问题是,我收到一个错误消息,说一个配置元素无法识别。该类如下:

[ConfigurationCollection(typeof(SectionItem), AddItemName = "Item", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class Sections : ConfigurationElementCollection
{
    public SectionItem this[int index]
    {
        get { return BaseGet(index) as SectionItem; }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    public new SectionItem this[string response]
    {
        get { return (SectionItem)BaseGet(response); }
        set
        {
            if (BaseGet(response) != null)
            {
                BaseRemoveAt(BaseIndexOf(BaseGet(response)));
            }
            BaseAdd(value);
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new SectionItem();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((SectionItem)element).Key;
    }
  }

而且还有SectionItem类:

public class SectionItem : ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get { return this["key"] as string; }
    }
}

如果我在Sections类中添加一个类型为SectionItems的配置属性,这对我来说是行不通的,因为我想要在配置文件的Section标签中拥有多个SectonItems。我已经搜索了解决方案,但我找到的一切都没有解决这个问题。

为了更好地理解我想要实现的目标,以下是我的配置文件的外观:

<configuration>
 <configSections>
  <section name="AdminConfig" type="XmlTest.AdminConfig, XmlTest"/>
 </configSections>
 <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
 </startup>

<AdminConfig>
 <Field name="field1" key="12345" path="asd"/>
  <Section>
    <Item key="12345"/>
    <Item key="54321"/>
  </Section>
 </AdminConfig>  
</configuration>
1个回答

17

好的,我已经找到了问题所在。虽然 Sections 类有这个 [ConfigurationCollection(typeof(SectionItem), AddItemName = "Item", CollectionType = ConfigurationElementCollectionType.BasicMap)],但我必须注释掉在 ConfigurationSection类中的属性,如下所示:

[ConfigurationProperty("sections")]
 [ConfigurationProperty("Section")]
 [ConfigurationCollection(typeof(Sections), AddItemName = "Item")]
 public Sections Sections
 {
    get
    {
      return (Sections)this["Section"];
    }
 }

现在这些物品被识别并且工作正常。


1
对于其他网络搜索者--ConfigurationCollection是帮助我的东西;'AddItemName'必须与您的目标XML元素标签匹配,以用于集合项类型。 - ryanwebjackson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接