0

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

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

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

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 是具有来自配置文件的数据的配置变量。

4

2 回答 2

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)
{
    // ...
}

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

于 2011-04-15T19:22:47.733 回答
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");
于 2011-04-15T18:58:31.190 回答