2012-07-09 85 views
1

我想有以下部分结构在我的app.config如何将属性添加到我的app.config配置集合中?

<MyConfig> 
    <NewsFeeds site="abc"> 
     <add name="first" /> 
    </NewsFeeds> 
    <NewsFeeds site="zyx"> 
     <add name="another" /> 
    </NewsFeeds> 
</MyConfig> 

我已经有MyConfig部分工作,但我不确定的NewsFeed集合应该如何进行编码,或者如果这种结构甚至有可能。现在,我有以下类到目前为止:

[ConfigurationCollection(typeof(NewsFeedConfig))] 
public class NewsFeedConfigCollection : ConfigurationElementCollection 
{ 
    protected override ConfigurationElement CreateNewElement() 
    { 
     return new NewsFeedConfig(); 
    } 

    protected override object GetElementKey(ConfigurationElement element) 
    { 
     return ((NewsFeedConfig)(element)).Name; 
    } 

    public NewsFeedConfig this[int idx] { get { return (NewsFeedConfig)BaseGet(idx); } } 
} 

public class NewsFeedConfig : ConfigurationElement 
{ 
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)] 
    public string Name 
    { 
     get { return (string)base["name"]; } 
     set { base["name"] = value; } 
    } 

    [ConfigurationProperty("source", IsRequired = true)] 
    public string Source 
    { 
     get { return (string)base["source"]; } 
     set { base["source"] = value; } 
    } 
} 

然而,这要求所有的新闻源是一个在新闻提要集合,然后我不得不通过增加Site属性,每个手工解析出来元件。这很好,但是有可能以上面定义的XML工作的方式来实现它吗?

回答

0

我想你会发现你的答案在这里:Sections must only appear once per config file! why?

您可能希望你的XML重组到更多的东西,如:

<MyConfig> 
    <NewsFeed site="abc"> 
    <Feeds> 
     <Feed name="first" /> 
    </Feeds> 
    </NewsFeed> 
    <NewsFeed site="zyx"> 
    <Feeds> 
     <Feed name="second" /> 
     <Feed name="third" /> 
     <Feed name="fourth" /> 
    </Feeds> 
    </NewsFeed> 
</MyConfig> 
相关问题