針對簡單設定檔 (如 site.config) 的讀寫需求,封裝 XmlDocument 兩大核心方法:ReadValue、UpdateValue。
<?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>
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 )。XmlReader (唯讀流式) / XmlWriter (寫入流式) / XDocument (LINQ to XML,功能更豐富)。