How to read key/value in xml file
17,975
Solution 1
Dictionary is your best choice to keep the data including the method to read attributes
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);
}
Solution 2
Below snippet looks most elegent and simple way to do your needs. Try out
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 ));
}
Please mark the answer if it is useful
![Arif YILMAZ](https://i.stack.imgur.com/BKqTy.png?s=256&g=1)
Author by
Arif YILMAZ
c#, mvc, web api, sql, t-sql, html5, jquery, css, angularjs
Updated on June 08, 2022Comments
-
Arif YILMAZ about 2 years
I am trying to build a console project which reads an ASP.NET project's web.config file. I need to read a value from the config. I am putting what I want to read from the web.config file.
<appSettings> <add key="LogoFrmNumber" value="001"/> <add key="LogoFrmPeriod" value="01"/> </appSettings>
I want to read LogoFrmNumber's value like I read regular xml file. How can I read that value.
here is my code to read web.config but I am stuck.
XDocument doc = XDocument.Load( "c://web.config" ); var values = doc.Descendants( "AppSettings" ); foreach ( var value in values ) { Console.WriteLine( value.Value ); } Console.ReadLine();
-
Georgi-it about 11 yearswhat declaration of elements ? if you mean the dictionary - yes it has to be <string, string> my mistake editing