我有一個 XML 檔案,它是由我的其他應用程式之一以自定義格式創建的。如下所示,現在我想將 FilePath 值更新為不同的路徑。我想根據 key 更新值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 值?
uj5u.com熱心網友回復:
使用 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");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430767.html
上一篇:使用子命令查找-exec
