remove元素的自定义配置无法识别的属性

时间:2015-05-23 18:58:00

标签: c# xml web-config

我有一个自定义配置部分,引发了以下错误:

Unrecognized attribute 'path'. Note that attribute names are case-sensitive.

本节的其余部分没有任何加载问题。但是,一旦我将<remove>元素添加到相关集合中,配置就无法加载。

以下是有问题的部分的代码:

[ConfigurationCollection(typeof(PathElement), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public class PathElementCollection : ConfigurationElementCollection
{
    public PathElementCollection()
    {
        // Load the default values...
        BaseAdd(new PathElement() { Path = "/content/" });
    }

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

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((PathElement)element).Path;
    }
}

public class PathElement : ConfigurationElement
{
    public const string PathPropertyName = "path";

    [ConfigurationProperty(PathPropertyName, IsRequired = true)]
    public string Path
    {
        get { return (string)this[PathPropertyName]; }
        set { this[PathPropertyName] = value; }
    }
}

我如何加载使用它的模块中的部分:

CustomSection configSection = (CustomSection)ConfigurationManager.GetSection(CustomSection.SectionName);

示例配置:

<ignoredPaths>
    <remove path="/content/" />
    <add path="/test/" />
</ignoredPaths>

有没有人对我做错了什么有任何想法?

1 个答案:

答案 0 :(得分:0)

您的课程应如下所示

    [XmlRoot("ignoredPaths")]
    public class IgnoredPaths
    {
        PathElementCollection paths {get;set;}
    }
    [XmlInclude(typeof(Remove))]
    [XmlInclude(typeof(Add))]
    public class PathElementCollection
    {
        [XmlAttribute("path")]
        public string path {get;set;}
    }
    [XmlRoot("remove")]
    public class Remove : PathElementCollection
    {
    }
    [XmlRoot("add")]
    public class Add : PathElementCollection
    {
    }​