簡體   English   中英

從xml中獲取鍵的值,然后在C#中將鍵值更改為xml?

[英]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");

                }
            }

如何在控制台中獲取密鑰並以XML設置值? 此行有一個例外:

String KeyAttribute = aNode.Attributes["key"].Value; 

如果您需要在appSettings部分下添加一些鍵。 閱讀如下的設置

XmlNodeList XList = appConfig.SelectNodes(“ // appSettings / *”);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM