2012-07-09 87 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> 
相關問題