Reputation: 23
I'm having troubles writing a configuration section for my application. All I need is to config a list of pairs which I would translate to an object. I have seen implementations using ConfigurationElement and ConfigurationElementCollection classes, but it looks horrible, and I actually forced my code and configuration to fit this solution. I do NOT want to use element with key-value attributes becuase it's not what I need. I want my configuration section to look like this:
<MySection>
<Option>
<City>aaa</City>
<Country>bbb</Country>
</Option>
<Option>
<City>ccc</City>
<Country>ddd</Country>
</Option>
<Option>
<City>eee</City>
<Country>fff</Country>
</Option>
</MySection>
Another oossible section:
<MySection>
<Option City="aaa" Country="bbb"/>
<Option City="ccc" Country="ddd"/>
<Option City="eee" Country="fff"/>
</MySection>
Is there any class that might help me parse this without forcing my code to do ugly stuff?
thank you
Upvotes: 1
Views: 188
Reputation: 2844
You could go for 2 options:
Create a custom configuration section at a similar question on How to add a xml in web.config? or have a loook at a basic example here: https://web.archive.org/web/20201202223151/http://www.4guysfromrolla.com/articles/020707-1.aspx
If you can store it in a simple list, go for a comma separated string in your appSettings:
<appSettings> <add key="countryName" value="CityA, CityC, CityD" /> <add key="countryName2" value="CityB, CityE" /> </appsettings>
And read it like this:
string[] citiesPerCountry = ConfigurationManager.AppSettings["countryName"].Split(',').Select(s => s.Trim()).ToArray();
Upvotes: 1