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>
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;
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";
You are searching for UserName but you have Username defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With