循环通过configrationsection使用C#读取它的元素

时间:2011-04-15 18:33:56

标签: c# configuration configurationsection

我有一个配置文件,例如:

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

如何读取配置以获取传递的keyname值。这是我写的方法:

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是配置变量,其中包含配置文件中的数据。

2 个答案:

答案 0 :(得分:1)

将您的配置文件加载到XmlDocument中,按名称获取XmlElement(您想要读取的设置值)并尝试使用代码。

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlfilename);

XmlElement elem = doc.GetElementByName("keyname");
var allDescendants = myElement.DescendantsAndSelf();
var allDescendantsWithAttributes = allDescendants.SelectMany(elem =>
    new[] { elem }.Concat(elem.Attributes().Cast<XContainer>()));

foreach (XContainer elementOrAttribute in allDescendantsWithAttributes)
{
    // ...
}

How to write a single LINQ to XML query to iterate through all the child elements & all the attributes of the child elements?

答案 1 :(得分:0)

将其转换为正确的XML并在节点内搜索:

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来获取值。

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