如何在web.config中添加xml?

Gul*_*han 5 .net c# asp.net wcf

我有一些复杂的数据用于xml格式的应用程序配置.我想在web.config中保留这个xml字符串.是否可以在web.config中添加一个大的xml字符串并在代码中获取它?

Joe*_*Joe 17

如果您不想编写配置节处理程序,可以将XML放在映射到的自定义配置节中IgnoreSectionHandler:

<configuration>
    <configSections>
      <section 
          name="myCustomElement" 
          type="System.Configuration.IgnoreSectionHandler" 
          allowLocation="false" />
    </configSections>
    ...
    <myCustomElement>
        ... complex XML ...
    </myCustomElement>
    ...
</configuration>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用任何XML API,如阅读XmlDocument,XDocument,XmlReader类.例如:

XmlDocument doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
XmlElement node = doc.SelectSingleNode("/configuration/myCustomElement") as XmlElement;
... etc ...
Run Code Online (Sandbox Code Playgroud)

  • <section> describeber必须放在<applicationSettings>中的<configuration> <configSections>和<myCustomElement>中 (2认同)

Ode*_*ded 6

有几种方法可以实现您的需求(一个可以全局和静态访问应用程序代码的XML片段):

  • web.config已经一个XML文件.你可以写一个自定义配置节(如描述这里为了从您的自定义XML获取数据).

  • 您可以对XML数据进行编码(所有<to &lt;,>to &gt,&to &amp;,"to &quote;)

  • 您可以将XML数据放在一个<![CDATA[]]>部分中

  • 不要web.config用于此,而是@Yuck评论的Settings文件

就易于开发和使用而言,最后一个选项是最好的选择.