1

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.

svick
  • 236,525
  • 50
  • 385
  • 514
w128
  • 4,680
  • 7
  • 42
  • 65

2 Answers2

2

Try using the Load() method instead of LoadXml()

doc.Load(config.FilePath);

I also sould suggest you have a look at XDocument instead of XmlDocument. LINQ will really be of use when getting that value from the config file.

Moriya
  • 7,750
  • 3
  • 35
  • 53
2

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");
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 1
    Thanks, very useful. Both answers (Animal's and yours) actually worked. However, instead of the above, I had to use the following code to get it to work: `var query = "/configuration/Custom/Level3/add[@value='s2']"; var dbElement1 = xdoc.XPathSelectElement(query); string key = dbElement1.Attribute("value").Value;` – w128 Jan 24 '13 at 12:30