c# - 仅写入一个 XML 属性,而不影响其余属性

标签 c# xml

我有以下内容,但它不适合我:

  static void SaveVersion(string configFile, string Version) 
  {
            XmlDocument config = new XmlDocument();
            config.Load(configFile);

            XmlNode appSettings = config.SelectSingleNode("configuration/appSettings");
            XmlNodeList appKids = appSettings.ChildNodes;

            foreach (XmlNode setting in appKids) 
            {

                if (setting.Attributes["key"].Value == "AgentVersion")
                    setting.Attributes["value"].Value = Version;
            }

            config.Save(configFile);
  }

我在 config.Load(configFile) 上加载的配置文件如下:

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
  </startup>

  <appSettings>
    <add key="AgentVersion" value="2.0.5" />
    <add key="ServerHostName" value="" />
    <add key="ServerIpAddress" value="127.0.0.1" />
    <add key="ServerPort" value="9001" />
  </appSettings>
</configuration>

我错过了什么吗?我认为它只会编辑特定的属性 AgentVersion 但它并没有真正做任何事情。

最佳答案

您知道ConfigurationManager吗?类(class)?您可以使用它来操作您的 app.config 文件,而无需手动执行任何操作。我认为你不应该重新发明轮子,除非你有充分的理由:

static void SaveVersion(string configFile, string version) 
{
    var myConfig = ConfigurationManager.OpenExeConfiguration(configFile);
    myConfig.AppSettings.Settings["AgentVersion"].Value = version;
    myConfig.Save();
}

关于c# - 仅写入一个 XML 属性,而不影响其余属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17179090/

相关文章:

c# - 更改 Gtk.Image 的单个像素

c# - Windows MVVM中的通用应用程序

Java XML - "1 counts of IllegalAnnotationExceptions"

c# - switch语句的when表达式中的匿名变量

c# - Windows Phone 8 开发 - 日志记录和 IOC 设计模式

c# - 重定向到 Session_end 事件的另一个页面

xml - 指定超过 1 个 Xml 根属性

java - 使用 DocumentBuilder 解析 XHTML 时出现无限循环 "parse"

c++ - 如何使用 msxml 解析器创建子元素?

java - NullPointerException TextView.setText(CharSequence),不清楚它如何仍然为空