【问题标题】:How can I include a CDATA section in a ConfigurationElement?如何在 ConfigurationElement 中包含 CDATA 部分?
【发布时间】:2010-09-30 03:36:21
【问题描述】:

我正在使用 .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>

我希望能够将 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>

【问题讨论】:

    标签: c# configuration configuration-files


    【解决方案1】:

    在您的 ConfigurationElement 子类中,尝试使用 XmlWriter.WriteCData 覆盖 SerializeElement 以写入您的数据,并使用 XmlReader.ReadContentAsString 覆盖 DeserializeElement 以将其读回。

    【讨论】:

    • 谢谢,我会试一试!
    【解决方案2】:

    在您的自定义配置元素类中,您需要覆盖方法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;
        }
    }
    

    我必须解决同样的问题。

    【讨论】:

    • 我认为这在 .net 4.5 中不起作用。在命中这些覆盖之前引发异常。
    猜你喜欢
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多