0

I have a configuration file, something like:

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

How can I read configuration to get the value of keyname passed. Here is the method that I wrote:

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 is the Configuration variable that has the data from the config file.

Sri Reddy
  • 6,832
  • 20
  • 70
  • 112

2 Answers2

1

Load your config file into XmlDocument, get XmlElement by name (setting value you want to read) and try following code.

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?

Community
  • 1
  • 1
Priyank
  • 10,503
  • 2
  • 27
  • 25
0

Convert it to proper XML and search within the nodes:

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

Just a quick note: if you convert it to XML, you can also use XPath to get the values.

System.Xml.XmlNode element = doc.SelectSingleNode("/NODE");
KamilDev
  • 718
  • 2
  • 7
  • 21
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93