[英]Getting a value of key from xml and change the key value to xml in c#?
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? 如何在控制台中获取密钥并以XML设置值? There is an exception on this line:
此行有一个例外:
String KeyAttribute = aNode.Attributes["key"].Value;
If you need to add some keys under appSettings section. 如果您需要在appSettings部分下添加一些键。 Read the appsettings as below
阅读如下的设置
XmlNodeList XList = appConfig.SelectNodes("//appSettings/*"); XmlNodeList XList = appConfig.SelectNodes(“ // appSettings / *”);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.