封裝 `System.Xml.XmlDocument` 常用操作,提供型別安全、例外透傳、資源釋放的簡潔 API,適用於中小型 XML 設定檔/資料檔管理。
using System;
using System.Data;
using System.IO;
using System.Xml;
public class XmlControl : IDisposable
{
private readonly string _xmlFilePath;
private XmlDocument _xmlDoc;
public XmlControl(string xmlFilePath)
{
_xmlFilePath = xmlFilePath ?? throw new ArgumentNullException(nameof(xmlFilePath));
_xmlDoc = new XmlDocument();
try { _xmlDoc.Load(_xmlFilePath); }
catch (Exception ex) { throw new XmlException($"載入 XML 失敗: {_xmlFilePath}", ex); }
}
/// XPath 查詢並回傳 DataView (適合直接繫結 GridView 等控制項)
public DataView GetData(string xpath)
{
var node = _xmlDoc.SelectSingleNode(xpath);
if (node == null) return new DataView(); // 或拋出例外
var ds = new DataSet();
using (var reader = new StringReader(node.OuterXml))
ds.ReadXml(reader);
return ds.Tables.Count > 0 ? ds.Tables[0].DefaultView : new DataView();
}
/// 更新節點內文
public void Replace(string xpath, string newContent)
{
var node = _xmlDoc.SelectSingleNode(xpath);
if (node == null) throw new XmlException($"節點不存在: {xpath}");
node.InnerText = newContent;
}
/// 刪除指定節點
public void Delete(string xpath)
{
var node = _xmlDoc.SelectSingleNode(xpath);
if (node == null) return; // 或拋出例外
node.ParentNode?.RemoveChild(node);
}
/// 插入子節點 (含一層孫節點)
public void InsertNode(string parentXPath, string childName, string elementName, string elementContent)
{
var parent = _xmlDoc.SelectSingleNode(parentXPath);
if (parent == null) throw new XmlException($"父節點不存在: {parentXPath}");
var child = _xmlDoc.CreateElement(childName);
parent.AppendChild(child);
var elem = _xmlDoc.CreateElement(elementName);
elem.InnerText = elementContent;
child.AppendChild(elem);
}
/// 插入帶屬性的元素
public void InsertElement(string parentXPath, string elementName, string attrName, string attrValue, string content)
{
var parent = _xmlDoc.SelectSingleNode(parentXPath);
if (parent == null) throw new XmlException($"父節點不存在: {parentXPath}");
var elem = _xmlDoc.CreateElement(elementName);
elem.SetAttribute(attrName, attrValue);
elem.InnerText = content;
parent.AppendChild(elem);
}
/// 插入無屬性元素
public void InsertElement(string parentXPath, string elementName, string content)
{
var parent = _xmlDoc.SelectSingleNode(parentXPath);
if (parent == null) throw new XmlException($"父節點不存在: {parentXPath}");
var elem = _xmlDoc.CreateElement(elementName);
elem.InnerText = content;
parent.AppendChild(elem);
}
/// 儲存變更並釋放資源
public void Save()
{
try { _xmlDoc.Save(_xmlFilePath); }
catch (Exception ex) { throw new XmlException($"儲存 XML 失敗: {_xmlFilePath}", ex); }
finally { Dispose(); }
}
public void Dispose()
{
if (_xmlDoc != null) { _xmlDoc = null; }
}
}
string path = Server.MapPath("TestXml.xml");
using (var xml = new XmlControl(path))
{
// 查詢繫結
// grid.DataSource = xml.GetData("Book/Authors[ISBN='0002']");
// grid.DataBind();
// 更新
// xml.Replace("Book/Authors[ISBN='0002']/Content", "新內容");
// 新增節點
// xml.InsertNode("Book", "Author", "ISBN", "0004");
// xml.InsertElement("Book/Author[ISBN='0004']", "Content", "內容");
// xml.InsertElement("Book/Author[ISBN='0004']", "Title", "Sex", "man", "值");
// 刪除
// xml.Delete("Book/Author[ISBN='0004']");
xml.Save(); // 統一寫入磁碟
}
`XmlControl` 為中小型 XML 操作提供開箱即用的封裝,涵蓋 CRUD 全流程。隨專案擴展,可漸進式遷移至 `XDocument` (LINQ to XML) 獲得更強型別、更流暢的查詢語法與更好效能。