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

我有一个配置文件,如:

   DEV     http://login.dev.server.com/Logon.asmx   http://login.ide.server.com/Logon.asmx     abc   123    

如何读取配置以获取传递的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是配置变量,其中包含配置文件中的数据。

那这个呢 ? 将其转换为正确的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"); 

将配置文件加载到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())); foreach (XContainer elementOrAttribute in allDescendantsWithAttributes) { // ... } 

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