Option Explicit
Private Const COMPACT As String = "compact.xml"
Private Const FORMATTED As String = "formatted.xml"
Private Sub FormatFileToFile(ByVal CompactFile As String, ByVal FormattedFile As String)
'Reads, parses, and reformats the XML "CompactFile" into an ADODB.Stream and writes
'it to "FormattedFile."
'
'Note the UTF-8 output never gets a BOM. If we want one we have to write it
'here explicitly after opening the Stream.
Dim wrtFormatted As MSXML2.MXXMLWriter
Dim stmFormatted As ADODB.Stream
Dim rdrFormatted As MSXML2.SAXXMLReader
Set stmFormatted = New ADODB.Stream
With stmFormatted
.open
.Type = adTypeBinary
Set wrtFormatted = New MSXML2.MXXMLWriter
With wrtFormatted
.omitXMLDeclaration = False
.standalone = True
.byteOrderMark = False 'If not set then .encoding is ignored.
.encoding = "utf-8" 'Even if .byteOrderMark = True,
'UTF-8 never gets a BOM.
.indent = True
.output = stmFormatted
Set rdrFormatted = New MSXML2.SAXXMLReader
With rdrFormatted
Set .contentHandler = wrtFormatted
Set .dtdHandler = wrtFormatted
Set .errorHandler = wrtFormatted
.putProperty "[URL unfurl="true"]http://xml.org/sax/properties/lexical-handler",[/URL] _
wrtFormatted
.putProperty "[URL unfurl="true"]http://xml.org/sax/properties/declaration-handler",[/URL] _
wrtFormatted
.parseURL CompactFile
End With
End With
.SaveToFile FormattedFile
.Close
End With
End Sub
Private Sub MakeLargeXML(ByVal FileName As String)
Dim F As Integer
Dim Level1 As Integer
Dim Level2 As Integer
F = FreeFile(0)
Open FileName For Output As #F
'Note: We're actually writing ANSI here for simplicity but it will
'be valid UTF-8 for our purposes.
Print #F, "<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>";
Print #F, "<document>";
For Level1 = 1 To 5000
Print #F, "<child instance="""; CStr(Level1); """>";
For Level2 = 1 To 100
Print #F, "<grandchild instance="""; CStr(Level2); """/>";
Next
Print #F, "</child>";
Next
Print #F, "</document>";
Close #F
End Sub
Private Sub Main()
'Skip making new compact XML file if we already have it.
On Error Resume Next
GetAttr COMPACT
If Err Then
On Error GoTo 0
MakeLargeXML COMPACT
End If
On Error GoTo 0
'Delete any existing formatted XML file before creating a new one.
On Error Resume Next
Kill FORMATTED
On Error GoTo 0
FormatFileToFile COMPACT, FORMATTED
MsgBox "Done!"
End Sub