[英]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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.