我将 MXXMLWriter60 与 SAXXMLReader60 结合使用以缩进输出并添加正确的编码标签。
输出内容是缩进的,但似乎始终忽略编码属性。为什么呢?
通过DOMDocument60.Load()加载的输入,如下所示:
<?xml version="1.0" encoding="iso-8859-15"?>
源码:
Private Sub SaveXmlAs(ByVal thisDOMDocument60 As DOMDocument60, ByVal thisEncoding As String, ByVal thisDestinationPath As String)
' Set properties on the XML writer - including BOM, XML declaration and encoding
Dim xmlWriter As New MXXMLWriter60
With xmlWriter
.Encoding = "iso-8859-15"
'.Version = "1.0"" encoding=""iso-8859-15" Hacky solution like hell...
.byteOrderMark = True
.omitXMLDeclaration = False
.indent = True
End With
' Set the XML writer to the SAX content handler.
Dim xmlReader As New SAXXMLReader60
With xmlReader
Set .contentHandler = xmlWriter
Set .dtdHandler = xmlWriter
Set .errorHandler = xmlWriter
' Now pass the DOM through the SAX handler, and it will call the writer
.Parse thisDOMDocument60
End With
' Let the writer do its thing
Open thisDestinationPath For Output As #1
Print #1, xmlWriter.output
Close #1
End Sub
输出始终如下:
<?xml version="1.0" standalone="no"?>
答案 0 :(得分:0)
我知道这个问题已经很老了,但我偶然发现了同样的问题,最后我找到了一个我喜欢分享的可行解决方案......也许它可以帮助面临同样问题的其他人。
使用 ADODB-Stream 对象作为具有匹配编码定义的 MXXMLWriter60 的输出目标会产生预期的 xml 标头。
Sub prettyPrintXML()
Dim stream As Object
Dim reader As New SAXXMLReader60
Dim writer As New MXXMLWriter60
Dim filename As String
Set stream = CreateObject("ADODB.Stream")
With stream
.Type = 2
.Charset = "iso-8859-1"
.Open
End With
With writer
.indent = True
.omitXMLDeclaration = False
.Encoding = "iso-8859-1"
.output = stream
End With
Set reader.contentHandler = writer
Set reader.errorHandler = writer
Call reader.putProperty("http://xml.org/sax/properties/declaration-handler", writer)
Call reader.putProperty("http://xml.org/sax/properties/lexical-handler", writer)
Call reader.Parse("<rootElement><levelOneItemOne><levelTwoItemOne></levelTwoItemOne></levelOneItemOne><levelOneItemTwo><levelTwoItemOne></levelTwoItemOne><levelTwoItemTwo></levelTwoItemTwo></levelOneItemTwo></rootElement>")
filename = ThisWorkbook.Path & "\prettyPrint.xml"
stream.SaveToFile filename, 2
stream.Close
End Sub
给出结果
<?xml version="1.0" encoding="iso-8859-1" standalone="no"?>
<rootElement>
<levelOneItemOne>
<levelTwoItemOne/>
</levelOneItemOne>
<levelOneItemTwo>
<levelTwoItemOne/>
<levelTwoItemTwo/>
</levelOneItemTwo>
</rootElement>
代码库来自这里:How can I pretty-print XML source using VB6 and MSXML?