2009-01-07 152 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