如何在xml文件中读取键/值 [英] How to read key/value in xml file

查看:87
本文介绍了如何在xml文件中读取键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个控制台项目,该项目读取ASP.NET项目的web.config文件。我需要从配置中读取一个值。我正在放入要从web.config文件读取的内容。

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>

我想读取LogoFrmNumber的值,就像读取常规xml文件一样。我该如何读取该值。

I want to read LogoFrmNumber's value like I read regular xml file. How can I read that value.

这是我读取web.config的代码,但我被卡住了。

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


推荐答案

词典是保持数据(包括读取属性的方法

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

这篇关于如何在xml文件中读取键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆