【问题标题】:Read sections from Config if name is unknown?如果名称未知,则从 Config 中读取部分?
【发布时间】:2012-12-26 14:20:27
【问题描述】:

我有一个简单的程序,可以让用户在自定义配置文件中添加一个部分,它的设置比显示的要多。我用所有配置的列表填充了一个 datagridview。我的问题是,填充列表框的方法不知道用户可能添加的所有部分的名称,我试图成为动态的。有没有一种简单的方法可以遍历这些部分并获取它们的名称?还是我必须创建一个部分、集合和元素才能做到这一点?

谢谢。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <configSections>
    <section name="Jason" type="SQLQueryOutput.SQLQueryOutputConfigSection, SQLQueryOutput, Version=1.0.0.0, Culture=neutral, PublicKeyToken=760d257b40400289" />
    <section name="Steve" type="SQLQueryOutput.SQLQueryOutputConfigSection, SQLQueryOutput, Version=1.0.0.0, Culture=neutral, PublicKeyToken=760d257b40400289" />
</configSections>
    <Jason OutputFilePath="C:\temp\jason.txt" />
    <Steve OutputFilePath="C:\temp\steve.txt" />
</configuration>

【问题讨论】:

  • 没有得到你想要达到的目标。如果要添加部分,为什么部分名称是未知的?或者您想在运行时添加任何部分(例如 nlog 部分)并检索它?

标签: c# .net xml configuration


【解决方案1】:

实际上你的configSections 元素也可以包含sectionGroup 元素。与Linq to Xml

XDocument xdoc = XDocument.Load(config_file_path);
var names =  xdoc.Root.Element("configSections")
                 .Descendants("section") // selects also sectionGroup/section
                 .Select(s => (string)s.Attribute("name"));

【讨论】:

    【解决方案2】:

    如何使用 Linq To Xml 解析您的配置文件。例如,

    var xDoc = XDocument.Load(configFile);
    var sections = xDoc.XPathSelectElements("//configSections/section")
                        .Select(x=>x.Attributes().ToDictionary(a=>a.Name,a=>a.Value))
                        .ToList();
    
    var name = sections[0]["name"];
    

    var outputFilePaths = xDoc.Root.Elements()
           .Where(d => d.Name.LocalName != "configSections")
           .ToDictionary(e => e.Name.LocalName, e => e.Attribute("OutputFilePath").Value);
    

    【讨论】:

    • 等等,真的有 NO 方法可以使用 .NET 的 ConfigurationManager 来做到这一点吗?像 .GetSections() 一样,然后为每个部分获取元素,等等......真的 需要 像使用 XDocument 的任何 XML 文件一样解析它吗?
    猜你喜欢
    • 1970-01-01
    • 2012-06-26
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2018-06-11
    相关资源
    最近更新 更多