namespace KeyValue
{
class Program
{
static void Main(string[] args)
{
XmlDocument appConfig = new XmlDocument();
appConfig.Load(@"C:\Users\manthan.rampal\Desktop\app.config");
var text = appConfig.InnerText;
// another try
XmlNode xNode = appConfig.CreateNode(XmlNodeType.Element, "add", "");
XmlAttribute xKey = appConfig.CreateAttribute("key");
XmlAttribute xValue = appConfig.CreateAttribute("value");
xKey.Value = "encryption.passcode";
xValue.Value = "kmggn2017";
xNode.Attributes.Append(xKey);
xNode.Attributes.Append(xValue);
XmlNodeList XList = appConfig.SelectNodes("//*");
foreach (XmlNode aNode in XList)
{
// grab the "id" attribute
String KeyAttribute = aNode.Attributes["key"].Value;
// check if that attribute even exists...
if (KeyAttribute == xKey.Value)
{
// if yes - read its current value
Console.WriteLine("Key Value Already Exists");
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
}
else
{
appConfig.GetElementsByTagName("appSettings")[0].InsertAfter(xNode,
appConfig.GetElementsByTagName("appSettings")[0].LastChild);
appConfig.Save(@"C:\Users\manthan.rampal\Desktop\app.config");
}
}
How can I get the keys in console and set the values in XML? There is an exception on this line:
String KeyAttribute = aNode.Attributes["key"].Value;
If you need to add some keys under appSettings section. Read the appsettings as below
XmlNodeList XList = appConfig.SelectNodes("//appSettings/*");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.