循环遍历configrationsection,使用c#读取它的'

本文关键字:读取 遍历 configrationsection 使用 循环 | 更新日期: 2023-09-27 17:50:14

我有一个配置文件,类似:

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

循环遍历configrationsection,使用c#读取它的'

将配置文件加载到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)
{
    // ...
}

如何编写一个LINQ to XML查询来遍历所有子元素&子元素的所有属性?

将其转换为适当的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");