2009-01-07 89 views
8

我正在使用.NET Fx 3.5并编写了自己的配置类,它们从ConfigurationSection/ConfigurationElement继承。目前,我最终的东西,看起来像这样在我的配置文件:如何在ConfigurationElement中包含CDATA部分?

<blah.mail> 
    <templates> 
     <add name="TemplateNbr1" subject="..." body="Hi!\r\nThis is a test.\r\n."> 
      <from address="[email protected]" /> 
     </add> 
    </templates> 
</blah.mail> 

我想是能够表达身体的template子节点(在上面的例子中add节点)至最终的东西,看起来像:

<blah.mail> 
    <templates> 
     <add name="TemplateNbr1" subject="..."> 
      <from address="[email protected]" /> 
      <body><![CDATA[Hi! 
This is a test. 
]]></body> 
     </add> 
    </templates> 
</blah.mail> 

回答

4

在你的ConfigurationElement子类,使用XmlWriter.WriteCData写你的数据尽量覆盖SerializeElement,并使用XmlReader.ReadContentAsString读回首要DeserializeElement。

+0

谢谢我会给这个镜头! – cfeduke 2009-01-20 23:14:31

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; 
    } 
} 

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

+1

我不认为这适用于.net 4.5。在这些覆盖命中之前抛出异常。 – JoshBerke 2013-07-01 18:54:56