<?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 查詢 |
File.Copy(path, path + ".bak", true);encoding="utf-8",xml.Save() 預設即為 UTF-8,若需指定編碼可用 XmlWriterSettings。XmlReader/XmlWriter 流式處理,避免一次載入整份 DOM 佔用記憶體。xmlns,XPath 查詢需註冊 XmlNamespaceManager,否則查不到節點。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 極方便,**新專案首選**。