描述:善用 XmlTextWriter 類別的格式化屬性,可以輕鬆提升 XML 資料的可讀性。
XML 最被稱道的一項優點,就是它同時能被機器與人類方便地讀取。任何文書編輯器都能開啟、修改 XML 資料。機器讀一份毫無縮排的 XML 從來不成問題,但人看起來就辛苦了。看看這份文件:
<WebSites> <WebSite><URL>https://xml.luohuedu.net/</URL><Title>【孟憲會之精彩世界】之 XML 開發者園地</Title><Desc>討論 XML 技術和 Web 技術的專業站點。</Desc></WebSite> <WebSite><URL>https://lucky_elove.www1.dotnetplayground.com/</URL> <Title>【孟憲會之精彩世界】之 .NET 開發者園地</Title><Desc>討論 .NET 技術和應用的專業站點。</Desc> </WebSite> </WebSites>
全部擠在一行,層級關係完全看不出來。要改善它,用 .NET 底下的 XmlTextWriter 就够了。
Formatting 設為 Formatting.Indented, writer 就會自動在元素之間插入換行與縮排。
Indentation 決定縮排的空格數,不設值的話預設是 2。
另外還有 IndentChar,可以改用 tab 或其他字元來填滿縮排位置。
完成格式化之後,把資料載入 XmlDocument 的 DOM 物件,再呼叫 WriteTo() 直接把整棵樹寫進 writer 即可。
Dim filePath As String = "c:\TestFormat.xml"
Dim writer As XmlTextWriter = New XmlTextWriter(filePath, Encoding.UTF8)
writer.Formatting = Formatting.Indented
writer.Indentation = 4
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml("<WebSites>" + _
"<WebSite><URL>https://xml.luohuedu.net/</URL><Title>【孟憲會之精彩世界】之" + _
"XML 開發者園地</Title><Desc>討論 XML 技術和 Web 技術的專業站點。</Desc></WebSite>" + _
"<WebSite><URL>https://lucky_elove.www1.dotnetplayground.com/</URL>" + _
"<Title>【孟憲會之精彩世界】之 .NET 開發者園地</Title>" + _
"<Desc>討論 .NET 技術和應用的專業站點。</Desc>" + _
"</WebSite></WebSites>")
doc.WriteTo(writer)
writer.Close()
string filePath = "c:\\TestFormat.xml"; XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.Indentation = 4; XmlDocument doc = new XmlDocument(); doc.LoadXml(@"<WebSites> <WebSite><URL>https://xml.luohuedu.net/</URL><Title>【孟憲會之精彩世界】之 XML 開發者園地</Title> <Desc>討論 XML 技術和 Web 技術的專業站點。</Desc></WebSite> <WebSite><URL>https://lucky_elove.www1.dotnetplayground.com/</URL> <Title>【孟憲會之精彩世界】之 .NET 開發者園地</Title> <Desc>討論 .NET 技術和應用的專業站點。</Desc> </WebSite> </WebSites>"); doc.WriteTo(writer); writer.Close();
<WebSites>
<WebSite>
<URL>https://xml.luohuedu.net/</URL>
<Title>【孟憲會之精彩世界】之 XML 開發者園地</Title>
<Desc>討論 XML 技術和 Web 技術的專業站點。</Desc>
</WebSite>
<WebSite>
<URL>https://lucky_elove.www1.dotnetplayground.com/</URL>
<Title>【孟憲會之精彩世界】之 .NET 開發者園地</Title>
<Desc>討論 .NET 技術和應用的專業站點。</Desc>
</WebSite>
</WebSites>
整整齊齊,層級一目了然。
第一,格式化只影響「沒有混合內容」的文件。若某個元素同時含有文字與子元素(mixed content),插入的空白會被視為有意義的內容,這時 Formatting 的設定就不該開啟。
第二,XmlTextWriter 在 .NET 中雖仍可用,但微軟已建議改用 XmlWriter.Create() 搭配 XmlWriterSettings 來達成同樣效果(設定 Indent = true 與 IndentChars)。新專案不妨直接採用後者,API 更一致,也能明確控制是否符合標準。