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

ASP.NET XML 讀寫操作實用類別:XmlDocument 讀取節點值、更新節點並保持格式化輸出

     編輯:關於ASP.NET

針對簡單設定檔 (如 site.config) 的讀寫需求,封裝 XmlDocument 兩大核心方法:ReadValue、UpdateValue。

範例 XML (model.xml)

<?xml version="1.0" encoding="utf-8"?>
<DrRoot>
  <SiteName>XML 操作示例</SiteName>
  <SiteUrl>www.abc.com.cn</SiteUrl>
  <SiteDescript>.NET 開源論壇</SiteDescript>
  <SiteKeyWord>XML 操作示例</SiteKeyWord>
  <FileType>gif|jpg|rar</FileType>
  <FileSize>1024</FileSize>
  <Filters>script|iframe</Filters>
  <FilterEvent>onload|onmouseover</FilterEvent>
  <BadWords>admin|webmaster|drbbs</BadWords>
  <DisallowIP>0.0.0.0</DisallowIP>
  <IsCloseReg>False</IsCloseReg>
  <IsCloseBBS>False</IsCloseBBS>
  <PostPay>5</PostPay>
  <ReplyPay>2</ReplyPay>
  <GoodPay>10</GoodPay>
  <DelPost>5</DelPost>
  <DelReply>2</DelReply>
  <CancleGood>10</CancleGood>
</DrRoot>

封裝類別 (XmlConfigHelper.cs)

public class XmlConfigHelper
{
    private readonly string _filePath;

    public XmlConfigHelper(string serverMapPath)
    {
        _filePath = serverMapPath;
    }

    /// 讀取指定節點的 InnerText,不存在回傳空字串
    public string ReadValue(string nodeName)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(_filePath);
        XmlNodeList nodes = doc.GetElementsByTagName(nodeName);
        return nodes.Count > 0 ? nodes[0].InnerText : string.Empty;
    }

    /// 更新指定節點的 InnerText 並格式化儲存
    public void UpdateValue(string nodeName, string newValue)
    {
        if (string.IsNullOrEmpty(ReadValue(nodeName))) return; // 節點不存在不處理

        XmlDocument doc = new XmlDocument();
        doc.Load(_filePath);
        XmlNodeList nodes = doc.GetElementsByTagName(nodeName);
        nodes[0].InnerText = newValue;

        // 使用 XmlTextWriter 保持縮排格式
        using (XmlTextWriter writer = new XmlTextWriter(new StreamWriter(_filePath, Encoding.UTF8)))
        {
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2;
            doc.WriteTo(writer);
        }
    }
}

使用範例

XmlConfigHelper helper = new XmlConfigHelper(Server.MapPath("~/App_Data/model.xml"));

// 讀取
string siteName = helper.ReadValue("SiteName"); // "XML 操作示例"
string fileSize = helper.ReadValue("FileSize"); // "1024"

// 更新
helper.UpdateValue("SiteName", "新站點名稱");
helper.UpdateValue("FileSize", "2048");

進階擴充建議

功能實作方向
強型別存取泛型方法 T Get<T>(string key) + Convert.ChangeType
快取機制靜態 ConcurrentDictionary 快取 XmlDocument,檔案變更時 (FileSystemWatcher) 失效重載
XPath 支援SelectSingleNode(xpath) 替代 GetElementsByTagName,支援屬性、巢狀路徑
交易式寫入寫入暫存檔 → File.Replace 原子取代,防止寫入中斷損壞原檔
加密敏感值連線字串、金鑰等欄位儲存前加密 (DPAPI/AES),讀取時解密

效能提醒

  • XmlDocument 將整份 XML 載入記憶體 (DOM),適合 小型設定檔 ( < 100KB )。
  • 大型 XML 請改用 XmlReader (唯讀流式) / XmlWriter (寫入流式) / XDocument (LINQ to XML,功能更豐富)。
  • 高併發讀取場景務必加入快取,避免重複 IO + 解析開銷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved