【问题标题】:Reading nested configuration section element of same type from web.config file从 web.config 文件中读取相同类型的嵌套配置节元素
【发布时间】:2013-07-09 23:14:23
【问题描述】:

好吧,这是一个棘手的问题,或者我只是不知道该怎么做。

我在创建和阅读自定义配置部分时遇到问题,例如:

<a>
 <b>
  <c/>
  <c/>
 </b>
</a>

我遇到的问题是使用 ConfigurationManager.GetSection("a") 读取以下配置:

<a>
 <b>
  <c>
   <c/>
  <c>
 </b>
</a>

有没有办法让它工作?

谢谢。

【问题讨论】:

  • 这不是您拥有的有效 XML。有错别字吗?
  • 不,本来就是这样的。
  • 第二个 sn-p 不是有效的 XML。无论您多么努力,它都不会解析。你有一个开放的 标签。另外在 中嵌套一个 标签,这样你就得到 非常难以阅读。

标签: c# asp.net configuration web-config configuration-management


【解决方案1】:

我的建议?抛弃配置管理器并将配置加载到 XDocument 中。假设您有一个如下所示的配置文件:

<Settings>
    <ApplicationSettings>
        <AppSetting1 Value="Test1" />
        <AppSetting2 Value="Test2" />
    </ApplicationSettings>
    <DeviceSettings>
        <DeviceSetting1 Value="Test3" />
        <DeviceSetting2 Value="Test4" />
    </DeviceSettings>
</Settings>

要从中获取值,您可以将配置加载到 XDocument 中:

XDocument xdoc = XDocument.Load(@"Path\to\file.xml");

然后:

String test1 = xdoc.Element("Settings").Element("ApplicationSettings").Element("Appsetting1").Attribute("Name").Value;

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 2021-11-09
    • 1970-01-01
    • 2018-06-03
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多