把 XML 讀進記憶體有兩條路:一是 XmlDocument 那種 DOM 方式,一次把整棵樹載入;二是 XmlTextReader 這類流式(pull)讀取器,讓你自己控制讀進的節奏。當文件很大、而你要的只是其中幾個欄位時,第二種明顯更省記憶體。
以下這個方法示範的就是流式做法:讀入一份單一商品的模擬結果 XML,把外層屬性填進自訂類別,再把每個 Location 底下的大量 Record 彙整成各自的 DataTable,最後以 Hashtable 按 Location ID 收攏起來。
public clsSimuResultByOneGoods GetOneGoodsSimulationXML(string PathAndFileName)
{
clsSimuResultByOneGoods OneGoods = new clsSimuResultByOneGoods(); // 自訂類別
Hashtable AllLocationResult = new Hashtable();
XmlTextReader r = new XmlTextReader(PathAndFileName);
string LocationID = "";
DataTable LocationTable = null;
while (r.Read())
{
// 進入元素節點
if (r.NodeType == XmlNodeType.Element)
{
switch (r.LocalName)
{
case "Result":
OneGoods.GoodsCode = r.GetAttribute("GoodsCode");
OneGoods.From = Convert.ToDateTime(r.GetAttribute("FromDate"));
OneGoods.To = Convert.ToDateTime(r.GetAttribute("ToDate"));
break;
case "Location":
LocationID = r.GetAttribute("ID");
LocationTable = new DataTable();
LocationTable.Columns.Add("Date", typeof(DateTime));
LocationTable.Columns.Add("SafetyStock", typeof(decimal));
LocationTable.Columns.Add("ForecastDemand",typeof(decimal));
LocationTable.Columns.Add("FinalOutput", typeof(decimal));
LocationTable.Columns.Add("FinalInput", typeof(decimal));
LocationTable.Columns.Add("SimuStock", typeof(decimal));
LocationTable.Columns.Add("SimuStockTime", typeof(decimal));
LocationTable.Columns.Add("ImportWorkDay", typeof(bool));
LocationTable.Columns.Add("ExportWorkDay", typeof(bool));
break;
case "Record":
if (LocationTable != null)
{
DataRow dr = LocationTable.NewRow();
dr["Date"] = Convert.ToDateTime(r.GetAttribute("Date"));
if (r.GetAttribute("SafetyStock") != null &&
r.GetAttribute("SafetyStock") != "")
dr["SafetyStock"] = Convert.ToDecimal(r.GetAttribute("SafetyStock"));
if (r.GetAttribute("ForecastDemand") != null &&
r.GetAttribute("ForecastDemand") != "")
dr["ForecastDemand"] = Convert.ToDecimal(r.GetAttribute("ForecastDemand"));
if (r.GetAttribute("FinalInput") != null &&
r.GetAttribute("FinalInput") != "")
dr["FinalInput"] = Convert.ToDecimal(r.GetAttribute("FinalInput"));
if (r.GetAttribute("FinalOutput") != null &&
r.GetAttribute("FinalOutput") != "")
dr["FinalOutput"] = Convert.ToDecimal(r.GetAttribute("FinalOutput"));
if (r.GetAttribute("SimuStock") != null &&
r.GetAttribute("SimuStock") != "")
dr["SimuStock"] = Convert.ToDecimal(r.GetAttribute("SimuStock"));
if (r.GetAttribute("SimuStockTime") != null &&
r.GetAttribute("SimuStockTime") != "")
dr["SimuStockTime"] = Convert.ToDecimal(r.GetAttribute("SimuStockTime"));
if (r.GetAttribute("ImportWorkDay") != null &&
r.GetAttribute("ImportWorkDay") != "")
dr["ImportWorkDay"] = Convert.ToBoolean(r.GetAttribute("ImportWorkDay"));
if (r.GetAttribute("ExportWorkDay") != null &&
r.GetAttribute("ExportWorkDay") != "")
dr["ExportWorkDay"] = Convert.ToBoolean(r.GetAttribute("ExportWorkDay"));
LocationTable.Rows.Add(dr);
}
break;
default:
break;
}
}
// 離開元素節點:Location 結束,就把整張表收進 Hashtable
else if (r.NodeType == XmlNodeType.EndElement)
{
switch (r.LocalName)
{
case "Location":
if (LocationTable != null)
{
LocationTable.AcceptChanges();
AllLocationResult.Add(LocationID, LocationTable);
LocationID = "";
LocationTable = null;
}
break;
default:
break;
}
}
}
OneGoods.AllLocationResult = AllLocationResult;
return OneGoods;
}
整個方法的骨架是一個 while (r.Read()) 迴圈。每一次 Read() 只往前推進一個節點,你可以透過 NodeType 判斷目前站在元素開始、元素結束,還是文字節點上。這種「讀到哪、處理到哪」的模式,讓記憶體用量與文件總大小無關,只與單一 Location 的資料量有關。
屬性一律用 GetAttribute 取,不需要建立節點物件;LocalName 則刻意取代 Name,這樣即使文件帶有命名空間前綴,也仍能正確比對到 Result、Location、Record 這幾個名稱。
「開表—填列—收表」的三段式是這段程式的關鍵設計:遇到 Location 開表並記下 ID,遇到 Record 就往表裡塞一列,遇到 </Location> 就 AcceptChanges() 後存入 Hashtable,同時把暫存變數清空,準備迎接下一段。收放之間,狀態始終只有一份,不會互相污染。
r.GetAttribute("SafetyStock") != "" 之後又呼叫一次 GetAttribute("SafetyStock") 才轉型。既然已經拿到字串,不如先存進區域變數再判斷、再轉換,既少一次內部查表,程式也更好讀。
XML 是外部輸入,內容不保證格式正確。Convert.ToDecimal 遇到髒資料會直接丟例外,中斷整個流程。改成 decimal.TryParse、DateTime.TryParse,失敗時給個預設值或記錄警告,穩定度會好很多。若資料來源固定且格式已知,也可以宣告 XmlReaderSettings 並掛上 ValidationEventHandler,在讀取階段就攔下不符合結構的文件。
XmlTextReader 包裝了底層資料流,用完應該以 using 區塊包起來,確保檔案 handle 確實釋放——這一點在反覆讀取大量檔案的批次作業中尤其重要。
流式讀取適合「大檔案、淺需求」;但如果後續要做隨機存取、任意跳點、或是需要回頭修改特定節點,那麼一次載入成 XmlDocument 反而更省事。選擇取決於你的存取模式,而不是檔案大小本身。