.NET中的自定义配置 - 使用元素而不是属性

时间:2012-08-15 16:31:08

标签: configuration app-config

在我看过的所有自定义配置示例中,似乎没有人使用元素来存储数据,例如

<data name="1">
<server>aServer</server>
<ip>anipaddress</ip>
</data>

这实际上可行吗?

我知道我可以使用这样的属性:

<data name="1" server="aServer" ip="anipaddress"/>

TIA

2 个答案:

答案 0 :(得分:0)

ConfigurationElement.DeserializeElement的默认实现不支持XmlNodeType.TextXmlNodeType.CDATA类型的节点,并抛出ConfigurationErrorsException,并显示以下错误消息:The configuration section cannot contain a CDATA or text element.

因此,要使用元素文本内容存储信息,请覆盖ConfigurationElement.DeserializeElement方法。

答案 1 :(得分:-1)

是的,你可以做到。

<configuration>  
    <configSections>
        <sectionGroup name="pageAppearanceGroup">
            <section 
            name="pageAppearance" 
            type="Samples.AspNet.PageAppearanceSection" 
            allowLocation="true" 
            allowDefinition="Everywhere"/>
       </sectionGroup>
     </configSections>

  <pageAppearanceGroup>
    <pageAppearance remoteOnly="true">
      <font name="TimesNewRoman" size="18"/>
      <color background="000000" foreground="FFFFFF"/>
    </pageAppearance>
  </pageAppearanceGroup>
</configuration>

然后访问变量

Samples.AspNet.PageAppearanceSection config = (Samples.AspNet.PageAppearanceSection)System.Configuration.ConfigurationManager.GetSection(
        "pageAppearanceGroup/pageAppearance");

    Response.Write("<h2>Settings in the PageAppearance Section:</h2>");
    Response.Write(string.Format("RemoteOnly: {0}<br>", 
        config.RemoteOnly));
etc....

检查此链接 http://msdn.microsoft.com/en-us/library/2tw134k3.aspx