如何迭代自定义配置节条目?

时间:2012-10-14 04:04:05

标签: asp.net .net

我的自定义配置部分如下所示:

  <MySection>
    <add name="a" value="111"/>
    <add name="b" value="222"/>
    <add name="c" value="333"/>
    ...
  </MySection>

我知道how to write a custom config section,但是如何遍历其所有条目?

问题已解决:http://msdn.microsoft.com/en-us/library/system.configuration.configurationelement(v=vs.100).aspx

2 个答案:

答案 0 :(得分:0)

使用'GetSection'(链接如下)。

// Get the AppSettings section.
var sect = (MySection)ConfigurationManager.GetSection("mysection");

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx

答案 1 :(得分:0)

如果你想解析你的部分使用:

var config = (SampleConfigurationSection)ConfigurationManager.GetSection("sampleConfiguration");

config.YourCustomProperty = "Hello World";

如果你想手动迭代XML元素(这是一个非常奇怪的要求),你可以使用LINQ to XML

using System.Xml.Linq;

....

var xml = XDocument.Load("path to your config file");

var section = from e in xml.Root.Elements("your section name").Elements()
              select e;

如果您需要动态项目,那么也许您可以使用 ConfigurationElementCollection ,然后解析您的部分并使用您的集合对象,而不是直接使用XML

相关问题