Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read app.config using XmlDocument

Tags:

c#

app-config

I have one app.exe.config file and I am trying to read it via XmlDocument. However, the following code is not working (getting the value as null):

XmlDocument appSettingsDoc = new XmlDocument();
appSettingsDoc.Load(@"C:\DBUpgraderConfig\DBUpgrader.exe.config");
XmlNode node = appSettingsDoc.SelectSingleNode("//appSettings");
XmlElement value = (XmlElement)node.SelectSingleNode("UserName");

Here is the XML:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="Server" value="Xeon-s7\MSSQL2008"/>
    <add key="Username" value=""/>
    <add key="Password" value=""/>
  </appSettings>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>
like image 910
Akshay J Avatar asked Oct 30 '14 12:10

Akshay J


3 Answers

You should compare the attribute key, instead of trying to get it as node name:

XmlElement value = (XmlElement)node.SelectSingleNode("//add[@key='Username']");

This will get you the add node. You can do whatever you want with it, including getting the attribute value.

string val = value.Attributes["value"].Value;
like image 103
Patrick Hofman Avatar answered Nov 17 '22 09:11

Patrick Hofman


This is a lot easier using an XPath expression:

var appSettingsDoc = XmlDocument.Load(@"C:\DBUpgraderConfig\DBUpgrader.exe.config");

var node = appSettingsDoc.XPathSelectElement("//configuration/appSettings/add[@key = 'Username']");

// for example:
node.Attribute["value"].Value = "John Doe";  
like image 36
nvoigt Avatar answered Nov 17 '22 07:11

nvoigt


You are searching for UserName but you have Username defined.

like image 1
Piotr Perak Avatar answered Nov 17 '22 08:11

Piotr Perak