.NET configuration with text elements

By default .NET configuration can’t contain any CDATA or text elements and if you not experienced following message

The configuration section cannot contain a CDATA or text element

than you’re lucky!

So basically you can’t do something like this:

If you look closely to ConfigurationElement class you’ll notice 2 useful methods:

  1. DeserializeElement
  2. SerializeElement

The tick is to use above methods to overcome limitation of .NET configuration elements structure. These methos are responsible for saving to/reading from configuration file.

Let’s have a class that will represent <settings>¬†.NET configuration element

The configuration property Name in class will represent XML <name> element value so it’s value will be persisted using .NET configuration mechanism.

Next we’ll write custom model class (POCO, DTO, whatever you call it) that will represent our XML structure.

The key thing is to give your class, properties proper names which will be used in serialization/deserialization process.

The last thing that is missing is to write DeserializeElement and SerializeElement methods implementation.

One thing to note here is to provide your own namespace otherwise you’ll end up with default that will spoil this pure XML strucure (visually).

So the final version of your custom configuration class looks like

Given above implementation and XML configuration strucure now it’s possible to get your settings like you’d use .NET configuration: