如何使用 C# 更新自定义格式 XML 文件?

How to update custom format XML file using C#?

我有一个 XML 文件,它是由我的另一个应用程序以自定义格式创建的。如下所示,现在我想将 FilePath 值更新为不同的路径。我想根据键 FilePath 更新值。我在 C# 中尝试了不同的逻辑,但它总是返回 Key 作为 null.

<?xml version="1.0" standalone="yes"?>
<Root>
  <Configuration>
    <Key>FilePath</Key>
    <Value>C:\UserData.xlsx</Value>
  </Configuration>
  <Configuration>
    <Key>FileSize</Key>
    <Value>1024</Value>
  </Configuration>
  <Configuration>
    <Key>SourceMachine</Key>
    <Value>17HRDPQSt</Value>
  </Configuration>
</Root>

C#代码:

XmlDocument doc = new XmlDocument();
doc.Load(xmlpath);
XmlNodeList aNodes = doc.SelectNodes("/Root/Configuration");

foreach (XmlNode aNode in aNodes)
{
    
    XmlAttribute idAttribute = aNode.Attributes["FilePath"];
    
    if (idAttribute != null)
    {
      
        string newValue = excelFilePath;
        
        if (string.IsNullOrEmpty(newValue))
        {
            idAttribute.Value = excelFilePath;
        }
    }
}

doc.Save(xmlpath);

如何更新 FilePath 值?

使用 Xml Linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication17
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement filePath = doc.Descendants("Configuration").Where(x => (string)x.Element("Key") == "FilePath").FirstOrDefault();
            filePath.SetElementValue("Value", "New File Path");
 
 
        }
    }
}