Search code examples
c#.netxmlxmldocumentmachine.config

Reading custom machine.config elements using XmlDocument?


In machine.config file there are elements written there by 3rd party software so it looks like this:

<configuration>
    <configSections>
    ...
    </configSections>

    ...

    <Custom>
        <Level1> ... 
        </Level1>

        <Level2> ... 
        </Level2>

        <Level3>
            <add key="key_text1" value="s1" />
            <add key="key_text2" value="s2" />
            <add key="key_text3" value="s3" />
        </Level3>
    </Custom>
</configuration>

I want to get e.g. a value ("s2") of "value" attribute where key="key_text2" from configuration/Custom/Level3 node. So far, I tried to open machine.config as an XML and work from there:

Configuration config = ConfigurationManager.OpenMachineConfiguration();
XmlDocument doc = new XmlDocument();
doc.LoadXml(config.FilePath);

however, I get XmlException "Data at the root level is invalid.". I also don't know how to use Configuration class methods directly to get this done. Any ideas would be appreciated.


Solution

  • Use RuntimeEnvironment.SystemConfigurationFile to get machine.config location:

    XmlDocument doc = new XmlDocument();
    doc.Load(RuntimeEnvironment.SystemConfigurationFile);
    

    Also why not to use Linq to Xml?

    XDocument xdoc = XDocument.Load(RuntimeEnvironment.SystemConfigurationFile);
    var element = xdoc.XPathSelectElement("//Custom/Level3/add[@value='s2']");
    if (element != null)
        key = (string)element.Attribute("key");