DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
用 XmlTextWriter 讓 XML 資料變得易讀
編輯:XML詳解     

描述:善用 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 即可。

VB.NET 程式碼

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()

C# 程式碼

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 更一致,也能明確控制是否符合標準。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved