如何读取xml文件中的键/值
本文关键字:文件 xml 何读取 读取 | 更新日期: 2023-09-27 18:16:27
我正在尝试构建一个读取ASP的控制台项目。. NET项目的web。配置文件。我需要从配置中读取值。我把我想从网上读的东西放进去。配置文件。
<appSettings>
<add key="LogoFrmNumber" value="001"/>
<add key="LogoFrmPeriod" value="01"/>
</appSettings>
我想读LogoFrmNumber的值,就像我读常规xml文件。如何读取该值
这是我的代码来读取web。
XDocument doc = XDocument.Load( "c://web.config" );
var values = doc.Descendants( "AppSettings" );
foreach ( var value in values )
{
Console.WriteLine( value.Value );
}
Console.ReadLine();
字典是保存数据的最佳选择,包括读取属性的方法
XDocument doc = XDocument.Load( "c://web.config" );
var elements = doc.Descendants( "AppSettings" );
Dictionary<string, string> keyValues = new Dictionary<string, string>();
for (int i = 0; i < elements.Count; i++)
{
string key = elements[i].Attributes["key"].Value.ToString();
string value = elements[i].Attributes["value"].Value.ToString();
keyValues.Add(key,value);
}
下面的代码片段看起来最优雅和简单的方式来满足您的需求。尝试
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = @"c:'web.config";
Configuration configuration=ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = configuration.AppSettings.Settings;
foreach (KeyValueConfigurationElement item in settings)
{
Console.WriteLine(string.Format("Key : {0} Value : {1}", item.Key, item.Value ));
}
如果答案是有用的请标记