gpt4 book ai didi

c# - 读取从控制台选择的 XML 标准配置文件

转载 作者:行者123 更新时间:2023-12-04 09:46:53 24 4
gpt4 key购买 nike

我创建了一个实际使用标准配置的 CLI 应用程序 app.Config文件。

在这个文件中,我放了一些小节,比如

 <typicsTable>
<mainSettings>
<add key="sheetNumber" value="1"/>
<add key="firstDataRow" value="2"/>
</mainSettings>
</typicsTable>

我实际上阅读了这些设置
NameValueCollection TypicsConversionTableSettings = (NameValueCollection)ConfigurationManager.GetSection("typicsTable/mainSettings");

int ctSheetNumber = Int32.Parse(TypicsConversionTableSettings["sheetNumber"]);
int ctFirstDataRow = Int32.Parse(TypicsConversionTableSettings["firstDataRow"]);

以这种方式一切正常。

我现在想做的是

1)我想要具有自定义名称的不同配置文件(即 test1.configtest2.config )并通过 CLI 获取正确的配置文件;

2) 切换到较少的“.net 配置文件”,并从标准 XML 文件中获取数据。

我现在专注于第 1 点,我尝试了不同的尝试,我使用了
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = @"C:\folderTest\conf1.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

但我绝对不知道如何阅读文件中的部分和小节。我怎样才能做到这一点?

最佳答案

我相信可以帮助您的类(class)是 System.Xml.Linq .

using System.Xml.Linq;

因此,第 1 部分会将文件加载到 XElement 中:
XElement xConfig = XElement.Load("app.simulated.config");

这是一个快速演示,说明如何遍历所有内容并使用匹配条件查找单个元素。
class Program
{
static void Main(string[] args)
{

Console.WriteLine("Iterating the config file values and attributes...");
Console.WriteLine("==================================================");
XElement xConfig = XElement.Load("app.simulated.config");
foreach (var element in xConfig.DescendantsAndSelf())
{
Console.WriteLine(element.Name);
foreach (var attribute in element.Attributes())
{
Console.WriteLine("\t" + attribute.Name + "," + attribute.Value);
}
}

Console.WriteLine();
Console.WriteLine("Finding a value using matching conditions.");
Console.WriteLine("==========================================");

XElement xel =
xConfig
.DescendantsAndSelf()
.FirstOrDefault(match =>
(match.Attribute("key") != null) &&
(match.Attribute("key").Value == "sheetNumber"));

Console.WriteLine(
"The value of 'sheetNumber' is " +
xel.Attribute("value").Value
);

// Pause
Console.ReadKey();
}
}

Console Output

Clone or Download这个例子来自 GitHub。

关于c# - 读取从控制台选择的 XML 标准配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62082171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com