How to read key/value in xml file

2019-07-16 01:00发布

问题:

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();

回答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);
            }  


回答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