如何在ConfigurationElement中包含CDATA部分?

cfe*_*uke 8 c# configuration configuration-files

我正在使用.NET Fx 3.5并编写了自己的配置类,这些类继承自ConfigurationSection/ConfigurationElement.目前我在配置文件中看起来像这样的东西:

<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>
Run Code Online (Sandbox Code Playgroud)

我希望能够将body表示为template(add上面示例中的节点)的子节点,最终得到如下内容:

<blah.mail>
    <templates>
        <add name="TemplateNbr1" subject="...">
            <from address="blah@hotmail.com" />
            <body><![CDATA[Hi!
This is a test.
]]></body>
        </add>
    </templates>
</blah.mail>
Run Code Online (Sandbox Code Playgroud)

fra*_*sek 5

在自定义配置元素类中,您需要覆盖方法OnDeserializeUnrecognizedElement.

例:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不得不解决同样的问题.


oef*_*efe 4

在 ConfigurationElement 子类中,尝试使用 XmlWriter.WriteCData 重写 SerializeElement 来写入数据,并使用 XmlReader.ReadContentAsString 重写 DeserializeElement 将其读回。