萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# XML 操作工具類 XmlControl:載入、查詢、增刪改、儲存完整封裝

類別設計目標

封裝 `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(); // 統一寫入磁碟
}

設計亮點與改進建議

  • IDisposable 模式:`using` 區塊自動釋放 `XmlDocument` 記憶體。
  • 例外豐富化:捕獲底層例外並包裝為 `XmlException`,附帶檔案路徑與 XPath,利於診斷。
  • XPath 注入風險:若 XPath 含使用者輸入,需驗證或參數化 (可改用 `XmlNode.SelectNodes` 配合 `XmlNamespaceManager`)。
  • 大檔案效能:`XmlDocument` 全量載入 DOM,大檔案建議改用 `XmlReader`/`XmlWriter` 流式處理或 `LINQ to XML` (`XDocument`)。
  • 命名空間支援:目前未處理命名空間,實務中需傳入 `XmlNamespaceManager`。

結語

`XmlControl` 為中小型 XML 操作提供開箱即用的封裝,涵蓋 CRUD 全流程。隨專案擴展,可漸進式遷移至 `XDocument` (LINQ to XML) 獲得更強型別、更流暢的查詢語法與更好效能。

copyright © 萬盛學電腦網 all rights reserved