views:

1546

answers:

3

I'm trying to create classes to read from my config file using ConfigurationSection and ConfigurationElementCollection but am having a hard time.

As an example of the config:


<PaymentMethodSettings>
  <PaymentMethods>
    <PaymentMethod name="blah blah" code="1"/>
    <PaymentMethod name="blah blah" code="42"/>
    <PaymentMethod name="blah blah" code="43"/>
    <Paymentmethod name="Base blah">
      <SubPaymentMethod name="blah blah" code="18"/>
      <SubPaymentMethod name="blah blah" code="28"/>
      <SubPaymentMethod name="blah blah" code="38"/>
    </Paymentmethod>
  </PaymentMethods>
</PaymentMethodSettings>
+2  A: 

This should help you figure out how to create configuration sections correctly, and then read from them.

DOK
+3  A: 

The magic here is to use ConfigurationSection classes.

These classes just need to contain properties that match 1:1 with your configuration schema. You use attributes to let .NET know which properties match which elements.

So, you could create PaymentMethod and have it inherit from ConfigurationSection

And you would create SubPaymentMethod and have it inherit from ConfigurationElement.

PaymentMethod would have a ConfigurationElementCollection of SubPaymentMethods in it as a property, that is how you wire up the complex types together.

You don't need to write your own XML parsing code.

public class PaymentSection : ConfigurationSection
{
   // Simple One
   [ConfigurationProperty("name")]]
   public String name
   {
      get { return this["name"]; }
      set { this["name"] = value; }
   }

}

etc...

See here for how to create the ConfigurationElementCollections so you can have nested types:

http://blogs.neudesic.com/blogs/jason_jung/archive/2006/08/08/208.aspx

FlySwat
A: 

link text

Mark