【问题标题】:How to use sections in an app.config that's in a web.config?如何使用 web.config 中的 app.config 中的部分?
【发布时间】:2013-08-26 19:20:20
【问题描述】:

我的 web.config 如下所示:

<configuration>
  <configSections>
    <appSettings configSource="Exampleapp.config" />
    <connectionStrings configSource="ExampleProd.config" />
  </configSections>
<configuration>

我的 app.config (Exampleapp.config) 如下所示:

<configSections>
  <sectionGroup name="exampleSettings">
    <section name="blah" type="System.Configuration.NameValueSectionHandler" />
    <section name="foo" type="System.Configuration.NameValueSectionHandler" />
  </sectionGroup>
</configSections>
<exampleSettings>
  <blah>
    <add key="me" value="1" />
  </blah>
  <foo>
    <add key="you" value="2" />
  </foo>
</exampleSettings>

我收到一条错误消息:XML 文档不能包含多个根级元素。我该如何解决这个问题?

【问题讨论】:

  • 为什么没有&lt;configuration&gt; 作为根?
  • @Nilesh 如果我进行配置,则会收到一条错误消息:configSource 文件的格式必须是包含该部分名称的元素。

标签: asp.net web-config app-config


【解决方案1】:

正如错误明确指出的那样, 您只需要在 XML 文件中有一个根元素。 将两个父元素放在一个父元素中,例如,

<rootEle>

<configSections>
  <sectionGroup name="exampleSettings">
     <section name="blah" type="System.Configuration.NameValueSectionHandler" />
     <section name="foo" type="System.Configuration.NameValueSectionHandler" />
  </sectionGroup>
</configSections>
<exampleSettings>
  <blah>
     <add key="me" value="1" />
  </blah>
  <foo>
     <add key="you" value="2" />
  </foo>
</exampleSettings>

</rootEle>

它应该可以工作。

【讨论】:

  • 无论我把什么作为根元素都会给出错误:未声明“x”元素。
  • 我认为在您的 web.configappSettings 应该直接在configuration 下,而不是在configSections 下。
【解决方案2】:

根据this post,您会收到该错误,因为 XML 文档必须只有 一个根元素,而您目前有两个。尝试类似:

<?xml version="1.0" encoding="utf-8"?>
<config>
     *Your code goes here*
</config>

【讨论】:

  • 无论我把什么作为根元素都会给出错误:未声明“x”元素。
  • @dotnetN00b,看看this post的答案。
猜你喜欢
  • 1970-01-01
  • 2010-10-11
  • 2011-06-07
  • 2012-02-18
  • 2010-10-10
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
相关资源
最近更新 更多