8

I'm using the .NET Fx 3.5 and have written my own configuration classes which inherit from ConfigurationSection/ConfigurationElement. Currently I end up with something that looks like this in my configuration file:

<blah.mail>
    <templates>
        <add name="TemplateNbr1" subject="..." body="Hi!\r\nThis is a test.\r\n.">
            <from address="blah@hotmail.com" />
        </add>
    </templates>
</blah.mail>

I would like to be able to express the body as a child node of template (which is the add node in the example above) to end up with something that looks like:

<blah.mail>
    <templates>
        <add name="TemplateNbr1" subject="...">
            <from address="blah@hotmail.com" />
            <body><![CDATA[Hi!
This is a test.
]]></body>
        </add>
    </templates>
</blah.mail>
cfeduke
  • 23,100
  • 10
  • 61
  • 65

2 Answers2

5

In your custom configuration element class you need to override method OnDeserializeUnrecognizedElement.

Example:

public class PluginConfigurationElement : ConfigurationElement
{
    public NameValueCollection CustomProperies { get; set; }

    public PluginConfigurationElement()
    {
        this.CustomProperties = new NameValueCollection();
    }

    protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)
    {
        this.CustomProperties.Add(elementName, reader.ReadString());
        return true;
    }
}

I had to solve the same issue.

Lucero
  • 59,176
  • 9
  • 122
  • 152
frantisek
  • 366
  • 1
  • 4
  • 8
4

In your ConfigurationElement subclass, try overriding SerializeElement using XmlWriter.WriteCData to write your data, and overriding DeserializeElement using XmlReader.ReadContentAsString to read it back.

oefe
  • 19,298
  • 7
  • 47
  • 66