雖然 XML Schema (XSD) 功能更強、支援型別,且 .NET 類別操作更便利,但 DTD 仍是 W3C 標準,廣泛用於非 .NET 系統的資料交換。為實現向後相容,有時必須在 .NET 產出的 XML 中內嵌 DTD 宣告。
DataSet.WriteXml(StreamB) 附加資料 → 關閉 Stream B 完成輸出Private Function GetDTD(DTDFilePath As String) As IO.FileStream
Dim fsDTD As New System.IO.FileStream(DTDFilePath, IO.FileMode.Open)
Dim srDTD As New IO.StreamReader(fsDTD)
' 僅為示範讀取動作,實際只需回傳 fsDTD
Return fsDTD
End Function
Dim StreamB As New System.IO.FileStream(
Server.MapPath("") & "FINAL.xml",
IO.FileMode.Create)
Dim swOutput As New IO.StreamWriter(StreamB)
FileMode.Create 會覆寫同名檔案;其他模式如 Append、OpenOrCreate 視需求選用。
Dim StreamA As IO.FileStream = GetDTD("path.dtd")
Dim byteArray(StreamA.Length) As Byte
StreamA.Read(byteArray, 0, StreamA.Length)
StreamA.Close()
' 寫入時排除最後一個字元(通常是 EOF 或換行),避免重複
StreamB.Write(byteArray, 0, byteArray.Length - 1)
注意:StreamReader 處理字元,而非位元組;此處直接用 FileStream.Read 處理位元組陣列更精確。
' 假設 myDataSet 已填入資料
myDataSet.WriteXml(StreamB)
' 關閉串流,完成檔案寫入
StreamB.Close()
WriteXml 多載支援直接寫入 Stream,無需中繼檔案,效能最佳。
[DTD File] → StreamA (FileStream) → Byte[] → StreamB (FileStream) ← DataSet.WriteXml()
↓
[FINAL.xml] (檔案系統)
此模式同樣適用於:
<?xml version="1.0"?>Close() 或 Dispose() 所有串流,釋放檔案鎖定。BufferedStream 或分塊讀寫,避免記憶體壓力。善用 FileStream 的可組合性,即可在 .NET 中優雅地實現「DTD 內嵌 XML」,滿足跨平台相容需求,同時保持程式碼簡潔高效。