using System.Xml;
public Config ReadConfig(string path)
{
var config = new Config();
using (XmlTextReader reader = new XmlTextReader(path))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "ServerPath":
reader.Read();
config.ServerPath = reader.Value;
break;
case "SmtpServer":
reader.Read();
config.SMTPServer = reader.Value;
break;
case "ConnectString":
reader.Read();
config.ConnectString = reader.Value;
break;
}
}
}
}
return config;
}
優點:速度快、記憶體佔用極低。缺點:唯讀、無法隨機存取、程式碼較繁瑣。
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode node = doc.SelectSingleNode("/config/ServerPath");
config.ServerPath = node?.InnerText;
優點:API 豐富、支援修改、XPath 查詢。缺點:大檔案記憶體壓力大。
using System.Xml.Linq;
XDocument doc = XDocument.Load(path);
config.ServerPath = (string)doc.Root.Element("ServerPath");
config.SMTPServer = (string)doc.Root.Element("SmtpServer");
// 或查詢
var items = doc.Descendants("Item").Select(e => new { Id = (int)e.Attribute("id"), Name = (string)e });
優點:語法簡潔、強型別轉換、支援建立/修改/查詢、效能優於 XmlDocument。推薦新專案首選。
[XmlRoot("Config")]
public class Config
{
public string ServerPath { get; set; }
public string SMTPServer { get; set; }
public string ConnectString { get; set; }
}
// 反序列化
Config config;
using (var fs = new FileStream(path, FileMode.Open))
{
config = (Config)new XmlSerializer(typeof(Config)).Deserialize(fs);
}
優點:強型別、程式碼最少、自動對應屬性。缺點:XML 結構需符合慣例、效能稍低於 LINQ to XML。
| 場景 | 推薦方法 |
|---|---|
| 超大 XML (上百 MB),唯讀、單次掃描 | XmlTextReader / XmlReader |
| 中小型 XML,需查詢、修改、儲存 | XDocument (LINQ to XML) |
| 固定結構配置檔,直接對應物件 | XmlSerializer |
| 舊版專案相容、需 XPath | XmlDocument |
XNamespace ns = "https://example.com/schema";
var elem = doc.Root.Element(ns + "ServerPath");
掌握四大方法特性,依專案需求選擇最適合的 XML 處理方式。