遍历configrationsection使用C#读它的元素 [英] Loop through the configrationsection to read it's elements using C#

查看:491
本文介绍了遍历configrationsection使用C#读它的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置文件,是这样的:

I have a configuration file, something like:

<logonurls>
  <othersettings>
    <setting name="DefaultEnv" serializeAs="String">
      <value>DEV</value>
    </setting>
  </othersettings>
  <urls>      
    <setting name="DEV" serializeAs="String">
      <value>http://login.dev.server.com/Logon.asmx</value>
    </setting>
    <setting name="IDE" serializeAs="String">
      <value>http://login.ide.server.com/Logon.asmx</value>
    </setting>
  </urls>
  <credentials>
    <setting name="LoginUserId" serializeAs="String">
      <value>abc</value>
    </setting>
    <setting name="LoginPassword" serializeAs="String">
      <value>123</value>
    </setting>
  </credentials>    
</logonurls>



我怎样才能读取配置获得通过的键名的值。下面是我写的方法:

How can I read configuration to get the value of keyname passed. Here is the method that I wrote:

private static string GetKeyValue(string keyname)
{
    string rtnvalue = String.Empty;
    try
    {
        ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("logonurls");
        foreach (ConfigurationSection section in sectionGroup.Sections)
        {
            //I want to loop through all the settings element of the section
        }
    }
    catch (Exception e)
    {
    }
    return rtnvalue;
}



配置是从配置文件的数据的配置变量。

config is the Configuration variable that has the data from the config file.

推荐答案

这个怎么样?
将其转换为正确的XML和节点内搜索:

what about this ? convert it to proper xml and search within the nodes:

        private static string GetKeyValue(string keyname) {     
        string rtnvalue = String.Empty;     
        try     {
            ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("logonurls");
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(sectionGroup);

            foreach (System.Xml.XmlNode node in doc.ChildNodes)         
            {             
                //I want to loop through all the settings element of the section         
                Console.WriteLine(node.Value);
            }     
        }     
        catch (Exception e)     
        {     
        }     return rtnvalue; 
    } 



只是一个快速注:如果您将其转换为XML,你也可以使用。XPath来获取值

just a quick note: if you convert it to xml , you can also use xpath to get the values.

System.Xml.XmlNode element = doc.SelectSingleNode("/NODE");

这篇关于遍历configrationsection使用C#读它的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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