从XML配置文件加载和检索键/值对

时间:2014-01-06 13:33:11

标签: c# .net xml

我希望能够使用C#.NET从XML配置文件中包含的键/值对中获取值。

e.g。

<add key="ConnectionString" value="whatever"/>

我在这里回答了我自己的问题,但是我有兴趣看到从XML中的键/值对加载和检索值的替代选项 - 也许有更简单或更简洁的方法?

2 个答案:

答案 0 :(得分:2)

ConfigurationManager提供对客户端应用程序的配置文件的访问。 您可以使用创建自定义部分并使用GetSection方法

来获取键/值对
<MyDictionary>
        <add key="JoinG." value="Gabriel.Boltniew@xxxx.com"/>
        <add key="Brancheau S." value="Steve.sd@xxxx.com"/>
        <add key="Cetrulo P." value="Paul.ds@xxxx.com"/>
        <add key="Chiu J." value="ds.Chiu@xxxx.com"/>
        <add key="D'Alessio S." value="dsd.sdd@ffdf.com"/>

NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("MyDictionary");

您可以使用ConfigurationManager.ConnectionStrings Property声明连接字符串,它会获取当前应用程序默认配置的ConnectionStringsSection数据。 您可以访问连接字符串

string conStr = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionStringName"]);

<强>更新

要定义自定义配置文件,请使用ExeConfigurationFileMap Class ConfigurationManager.OpenMappedExeConfiguration方法将客户端指定的配置文件作为system.Configuration.Configuration对象打开。

 ExeConfigurationFileMap custmConfg = new ExeConfigurationFileMap();
 custmConfg.ExeConfigFilename = @"d:\test\test.XML";
 Configuration config = ConfigurationManager.OpenMappedExeConfiguration(custmConfg, ConfigurationUserLevel.None);

NameValueCollection coll = (NameValueCollection)ConfigurationManager.GetSection("SectionName");

答案 1 :(得分:1)

获取配置文件,在我的情况下包含在我的ASP.NET服务器应用程序的根目录中:

var doc = XDocument.Load(Server.MapPath("~") + "\\MyConfigFile.config");

使用LINQ获取键/值对(在下面的LINQ查询中,我们首先寻找'add'元素的后代,然后我们正在寻找第一个具有'key'属性匹配'ConnectionString'的节点,然后我们得到'value'属性的值:

var connectionString = doc.Descendants("add")
    .First(node => (string)node.Attribute("key") == "ConnectionString")
    .Attribute("value").Value;

获取方括号内指定的键的值:

var connectionString = parameters["ConnectionString"];

XDocument类还包含用于更新并将更改保存回物理文件的方法。

相关问题