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

C# 讀取 XML 文件的多種方法比較

     編輯:關於C#

方法一:XmlTextReader (唯讀、前向、流式、低記憶體)


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 (DOM、完整載入記憶體、支援 XPath)


XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode node = doc.SelectSingleNode("/config/ServerPath");
config.ServerPath = node?.InnerText;

優點:API 豐富、支援修改、XPath 查詢。缺點:大檔案記憶體壓力大。

方法三:XDocument / LINQ to XML (現代、語法優雅、功能強)


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。推薦新專案首選。

方法四:XmlSerializer (物件序列化/反序列化)


[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
舊版專案相容、需 XPathXmlDocument

命名空間處理提示


XNamespace ns = "https://example.com/schema";
var elem = doc.Root.Element(ns + "ServerPath");

掌握四大方法特性,依專案需求選擇最適合的 XML 處理方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved