You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# .NET程序能读取XML但无法写入的问题求助

问题分析与解决方案

核心问题是:你只修改了内存中XmlDocument对象的节点内容,没有调用Save方法将修改后的内容写入磁盘文件,所以XML文件不会有任何变化。

修复步骤

在修改完节点的InnerText后,必须调用XmlDocument.Save()方法,将内存中的XML结构持久化到文件中。修改你的写入代码如下:

Key = Console.ReadKey();

switch(Key.KeyChar)
{
    case '1':
        SaveFile.DocumentElement.SelectSingleNode("/fractionator-save/output-type").InnerText = "Hours";
        SaveFile.Save("fractionator-save.xml"); // 新增保存操作
        return Output.Hours;
    case '2':
        SaveFile.DocumentElement.SelectSingleNode("/fractionator-save/output-type").InnerText = "Minutes";
        SaveFile.Save("fractionator-save.xml"); // 新增保存操作
        return Output.Minutes;
    case '3':
        SaveFile.DocumentElement.SelectSingleNode("/fractionator-save/output-type").InnerText = "Seconds";
        SaveFile.Save("fractionator-save.xml"); // 新增保存操作
        return Output.Seconds;
    case '4':
        SaveFile.DocumentElement.SelectSingleNode("/fractionator-save/output-type").InnerText = "Frames";
        SaveFile.Save("fractionator-save.xml"); // 新增保存操作
        return Output.Frames;
    default:
        InvalidInput = true;
        Console.WriteLine("Error: Invalid input.");
        break;
}

额外注意事项

  • 路径正确性:确保"fractionator-save.xml"的路径是正确的,若程序运行的当前工作目录不是文件所在目录,建议使用绝对路径(比如Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fractionator-save.xml"))
  • 静态变量的一致性:如果SaveFile是静态变量,要确保在修改前它已经正确加载了文件,且没有被其他代码重新实例化导致修改丢失
  • 可选优化(XDocument):如果是.NET Framework 3.5及以上,推荐使用更简洁的XDocument来处理XML,读写代码会更直观:
    // 读取
    var doc = XDocument.Load("fractionator-save.xml");
    var outputType = doc.Root.Element("output-type").Value;
    
    // 修改并保存
    doc.Root.Element("output-type").Value = "Hours";
    doc.Save("fractionator-save.xml");
    

内容的提问来源于stack exchange,提问作者Tyll'a

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:36:13