views:

1353

answers:

4

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="[email protected]" />
        </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="[email protected]" />
            <body><![CDATA[Hi!
This is a test.
]]></body>
        </add>
    </templates>
</blah.mail>
+2  A: 

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
Thanks I'll give this a shot!
cfeduke
+2  A: 

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.

frantisek
+2  A: 

I created a generic solution using this approach. I have encapsulated the functionality into a class called CDataConfigurationElement. You will then have to decorate the property with a corresponding CDataCOnfigurationProperty attribute. Full source code is available here.

jake.stateresa
thank you very much for the source code. well designed and great example
ala
A: 

no puedo votar pero frantisek solucionó mi problema.

Ahora la solución de jake.stateresa es una buena opción cuando el archivo de configuracion es un poco más complejo.

Gracias