XML 是可擴充的標記語言,企業可以自訂一套資料格式,資料照著這個格式在網路上傳遞,再由 XSLT 轉成使用者想看的樣子——格式不相容的問題就這樣解掉了。對程式設計師而言,這正是 XML 最迷人的地方。
本文不談 XML 的優點,而是談 C# 裡該怎麼讀它。
在程式中操作 XML 一般有兩條路:DOM(文件物件模型)與流模型。
DOM 的長處是功能完整:可以編輯與更新文件、可以隨機存取任意節點、可以搭配 XPath 查詢。缺點也很明確——它必須一次把整份文件載入記憶體,遇到大型文件就是資源壓力。
流模型正好補上這塊:它一次只處理當前節點,記憶體中隨時只有一個節點的資料。代價是它唯讀且只能往前,無法在文件裡往回導航。兩者各有千秋,實務上也常見混用的情況。以下專注在讀取,因此聚焦流模型。
流模型每次迭代一個節點,適合大文件,記憶體佔用極小。它有兩種變體:
推模型(SAX)靠事件驅動,每遇到一個節點就觸發一個事件,開發者必須為每個事件撰寫處理常式。這樣的寫法僵硬又繁瑣。
拉模型則是 .NET 採用的方案:遍歷文件時,由程式主動把感興趣的部分從讀取器中「拉」出來,不需要觸發事件,允許以命令式的方式存取文件。彈性大幅提升;在效能上,拉模型可以選擇性處理節點,而 SAX 每遇到一個節點都要通知用戶端,因此拉模型通常能讓整體應用效率更好。.NET 中拉模型由 XmlReader 類別實作。
本文聚焦 XmlTextReader。它提供 XML 讀取功能,會驗證文件是否格式良好;若不然,讀取過程會丟出 XmlException。你可以用它的方法讀取、篩選節點,並取得節點名稱與值。
請記住一個比喻:XML 檔就像水源,閘門一開水就流出來,流過就是流過,不能回頭。記憶體中任何時刻只有當前節點,要往下走就呼叫 Read()。
下面這個類別把常用操作都封裝好了:遍歷取值、取得節點型別、依型別過濾、只取文字內容、讀取屬性、讀取命名空間,以及完整還原整份文件。
namespace XMLReading
{
using System;
using System.Xml;
using System.Windows.Forms;
/// <summary>XML 檔案讀取器</summary>
public class XmlReader : IDisposable
{
private string _XMLPath;
private const string _errMsg = "Error Occurred While Reading ";
private ListBox _listBox;
private XmlTextReader XMLTxtRd;
public XmlReader() { this._XMLPath = string.Empty; }
public XmlReader(string _XMLPath, ListBox _listBox)
{
this._xmlPath = _XMLPath;
this._listBox = _listBox;
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
if (this.XMLTxtRd != null) { this.XMLTxtRd.Close(); this.XMLTxtRd = null; }
this._XMLPath = null;
}
public ListBox listBox
{
get { return this._listBox; }
set { this._listBox = value; }
}
public string XMLPath
{
get { return this._XMLPath; }
set { this._XMLPath = value; }
}
/// 遍歷整份 XML,把每個節點的值放進清單
public void EachXML()
{
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._XMLPath);
try
{
while (XMLTxtRd.Read())
this._listBox.Items.Add(this.XMLTxtRd.Value);
}
catch (XmlException exp)
{
throw new XmlException(_errMsg + this._XMLPath + exp.ToString());
}
finally
{
if (this.XMLTxtRd != null) this.XMLTxtRd.Close();
}
}
/// 取得每個節點的型別
public void ReadXMLByNodeType()
{
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._XMLPath);
try
{
while (XMLTxtRd.Read())
this._listBox.Items.Add(this.XMLTxtRd.NodeType.ToString());
}
catch (XmlException exp)
{
throw new XmlException(_errMsg + this._XMLPath + exp.ToString());
}
finally
{
if (this.XMLTxtRd != null) this.XMLTxtRd.Close();
}
}
/// 依節點型別過濾
public void FilterByNodeType(XmlNodeType[] XMLNType)
{
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._XMLPath);
try
{
while (XMLTxtRd.Read())
{
for (int i = 0; i < XMLNType.Length; i++)
{
if (xmlTxtRd.NodeType == XMLNType[i])
this._listBox.Items.Add(xmlTxtRd.Name + " is Type " + XMLTxtRd.NodeType.ToString());
}
}
}
finally
{
if (this.XMLTxtRd != null) this.XMLTxtRd.Close();
}
}
/// 只取文字節點的值
public void ReadXMLTextValue()
{
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._XMLPath);
try
{
while (XMLTxtRd.Read())
if (xmlTxtRd.NodeType == XmlNodeType.Text)
this._listBox.Items.Add(XMLTxtRd.Value);
}
finally
{
if (this.XMLTxtRd != null) this.XMLTxtRd.Close();
}
}
/// 讀取屬性:HasAttributes 判斷、MoveToNextAttribute 逐個走訪
public void ReadXMLAttributes()
{
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._XMLPath);
try
{
while (XMLTxtRd.Read())
{
if (xmlTxtRd.NodeType != XmlNodeType.Element) continue;
if (XMLTxtRd.HasAttributes)
{
this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has "
+ XMLTxtRd.AttributeCount + " Attributes");
while (XMLTxtRd.MoveToNextAttribute())
this._listBox.Items.Add(xmlTxtRd.Name + " = " + XMLTxtRd.Value);
}
else
{
this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has no Attribute");
}
this._listBox.Items.Add("");
}
}
finally
{
if (this.XMLTxtRd != null) this.XMLTxtRd.Close();
}
}
/// 讀取命名空間:Prefix 不為空即代表帶有前綴
public void ReadXMLNamespace()
{
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._XMLPath);
try
{
while (XMLTxtRd.Read())
{
if (xmlTxtRd.NodeType == XmlNodeType.Element && XMLTxtRd.Prefix != "")
{
this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix
+ " is associated with namespace " + XMLTxtRd.NamespaceURI);
this._listBox.Items.Add("The Element with the local name "
+ xmlTxtRd.LocalName + " is associated with the namespace "
+ XMLTxtRd.NamespaceURI);
}
if (xmlTxtRd.NodeType == XmlNodeType.Element && XMLTxtRd.HasAttributes)
{
while (XMLTxtRd.MoveToNextAttribute())
{
if (XMLTxtRd.Prefix != "")
{
this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix
+ " is associated with namespace " + XMLTxtRd.NamespaceURI);
this._listBox.Items.Add("The Attribute with the local name "
+ xmlTxtRd.LocalName + " is associated with the namespace "
+ XMLTxtRd.NamespaceURI);
}
}
}
}
}
finally
{
if (this.XMLTxtRd != null) this.XMLTxtRd.Close();
}
}
/// 依序還原整份 XML 文件
public void ReadXML()
{
string attAndEle = string.Empty;
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._XMLPath);
try
{
while (XMLTxtRd.Read())
{
if (xmlTxtRd.NodeType == XmlNodeType.XmlDeclaration)
this._listBox.Items.Add(string.Format("<?{0} {1} ?>", xmlTxtRd.Name, XMLTxtRd.Value));
else if (xmlTxtRd.NodeType == XmlNodeType.Element)
{
attAndEle = string.Format("<{0} ", xmlTxtRd.Name);
if (XMLTxtRd.HasAttributes)
{
while (XMLTxtRd.MoveToNextAttribute())
attAndEle += string.Format("{0}='{1}' ", xmlTxtRd.Name, XMLTxtRd.Value);
}
this._listBox.Items.Add(attAndEle.Trim() + ">");
}
else if (xmlTxtRd.NodeType == XmlNodeType.EndElement)
this._listBox.Items.Add(string.Format("</{0}>", XMLTxtRd.Name));
else if (xmlTxtRd.NodeType == XmlNodeType.Text)
this._listBox.Items.Add(XMLTxtRd.Value);
}
}
finally
{
if (this.XMLTxtRd != null) this.XMLTxtRd.Close();
}
}
}
}
把上面用到的 API 整理成對照,讀起來更清楚:
Read():讀取下一個節點,讀到尾端後回傳 false,是整個迴圈的心臟。NodeType:回傳當前節點型別,常見的有 Element、EndElement、XmlDeclaration、Text。HasAttributes:當前節點是否帶有屬性。Name / LocalName / Prefix:節點的完整名稱、區域名稱與前綴。Value:節點的值。NamespaceURI:節點所屬命名空間的 URI。MoveToNextAttribute():移到下一個屬性,搭配 while 迴圈就能把屬性全部掃過。示範畫面共七個按鈕:遍歷取值、取節點型別、依型別過濾、只取文字、取屬性、取命名空間、顯示整份文件——對應上面七個方法,剛好可以逐一驗證各項 API 的行為。