How to read key/value in xml file

有些话、适合烂在心里 提交于 2019-12-24 00:17:46

问题


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



来源:https://stackoverflow.com/questions/16872575/how-to-read-key-value-in-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!