首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

C# XML 文件操作完整指南:修改節點值、屬性值、三種寫法比較

     編輯:ASP.NET 基礎

範例 XML 結構

<?xml version="1.0" encoding="utf-8"?>
<subtitles>
  <info>
    <content>最新通告:五一放假七天!請各教員悉知</content>
    <speed>4</speed>
    <color>red</color>
  </info>
</subtitles>

方法一:XmlDocument 遍歷子節點修改 元素內文

string filePath = HttpContext.Current.Server.MapPath("~/App_Data/XMLFile.xml");
XmlDocument xml = new XmlDocument();
xml.Load(filePath);

XmlNode root = xml.DocumentElement; // 
foreach (XmlNode node in root.ChildNodes) // 
{
    if (node.Name == "info")
    {
        node["content"].InnerText = "新通告內容";
        node["speed"].InnerText = "5";
        node["color"].InnerText = "blue";
    }
}
xml.Save(filePath);

✅ 適合:結構固定、需一次更新多個子元素。
⚠️ 注意:node["name"] 若不存在回傳 null,存取 .InnerText 會拋例外,建議先 if (node["content"] != null) 判斷。

方法二:SelectSingleNode + XmlAttribute 修改 屬性值

XmlDocument doc = new XmlDocument();
doc.LoadXml("<fsdlconfig userName=\"ss\" password=\"134\" />"); // 或 doc.Load(filePath)

XmlAttribute attr = (XmlAttribute)doc.SelectSingleNode("/fsdlconfig/@userName");
Console.WriteLine("修改前:" + attr.Value); // ss
attr.Value = "test";
string updatedXml = doc.OuterXml; // 取得修改後字串
// doc.Save(filePath); // 若需存檔

✅ 適合:精準定位單一屬性,XPath 表達力強(//node/@attr、/root/child[@id='5']/@name)。

方法三:XmlElement.SetAttribute 修改/新增屬性

XmlDocument doc = new XmlDocument();
doc.LoadXml("<fsdlconfig userName=\"ss\" password=\"134\" />");

XmlElement root = doc.DocumentElement; // 或 doc.FirstChild
root.SetAttribute("userName", "test"); // 不存在則新增,存在則覆蓋
string updatedXml = doc.OuterXml;

✅ 適合:不想寫 XPath、直觀「設定屬性」語意,且自動處理屬性不存在的情況。

三種寫法快速比較

場景推薦方法關鍵 API
修改多個子元素內文方法一XmlNode["childName"].InnerText
修改單一已知屬性方法三XmlElement.SetAttribute()
條件式查找屬性(如:id=5 的節點的 name 屬性)方法二SelectSingleNode("/root/node[@id='5']/@name")
大量異動效能考量方法一/三避免重複 XPath 查詢

最佳實務建議

  1. 儲存前備份:File.Copy(path, path + ".bak", true);
  2. 編碼一致:XML 宣告 encoding="utf-8",xml.Save() 預設即為 UTF-8,若需指定編碼可用 XmlWriterSettings。
  3. 大檔案改用 XmlReader/XmlWriter 流式處理,避免一次載入整份 DOM 佔用記憶體。
  4. 命名空間:若 XML 有 xmlns,XPath 查詢需註冊 XmlNamespaceManager,否則查不到節點。

補充:LINQ to XML (現代寫法,.NET 3.5+)

using System.Xml.Linq;

XDocument doc = XDocument.Load(filePath);
doc.Root.Element("info").Element("content").Value = "新內容";
doc.Root.Element("info").Element("speed").Value = "6";
doc.Root.Element("info").SetAttributeValue("version", "2.0"); // 修改/新增屬性
doc.Save(filePath);

✅ 語法更簡潔、支援 LINQ 查詢、物件初始化器建構 XML 極方便,**新專案首選**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved