2011-04-15 88 views
0

元素我有一個配置文件,是這樣的:循環遍歷configrationsection讀它使用C#

<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是配置變量,它具有來自配置文件的數據。

回答

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"); 
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?