Sub FormatDocToFile(ByVal Doc, ByVal FileName As String)
'Reformats the DOMDocument "Doc" into an ADODB.Stream
'and writes it to the specified file.
'
'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 rdrdom As MSXML2.SAXXMLReader
Dim rdrdom As Object
Set rdrdom = CreateObject("MSXML2.SAXXMLReader.6.0")
'Dim wtrFormatted As MSXML2.MXXMLWriter
'Set stmFormatted = New ADODB.Stream
Dim stmFormatted As Object
Set stmFormatted = CreateObject("ADODB.Stream")
With stmFormatted
.Open
.Type = 1 'adTypeBinary
Set wtrFormatted = New MSXML2.MXXMLWriter
With wtrFormatted
.omitXMLDeclaration = False
.standalone = True
.byteOrderMark = False 'If not set (even to False) then
'.encoding is ignored.
.Encoding = "utf-8" 'Even if .byteOrderMark = True
'UTF-8 never gets a BOM.
.indent = True
.output = stmFormatted
Set rdrdom = New MSXML2.SAXXMLReader
With rdrdom
Set .contentHandler = wtrFormatted
Set .dtdHandler = wtrFormatted
Set .errorHandler = wtrFormatted
.putProperty "http://xml.org/sax/properties/lexical-handler", wtrFormatted
.putProperty "http://xml.org/sax/properties/declaration-handler", wtrFormatted
.Parse Doc
End With
End With
.SaveToFile FileName
.Close
End With
End Sub