我正在使用“如何使 XMLDOMDocument 包含 XML 声明?”中看到的代码变体。(也可以在MSDN上看到。如果我将编码更改为“UTF-16”,人们会认为它会输出为 UTF-16……而且它“确实”……通过查看文本编辑器中的输出; 但是在十六进制编辑器中检查它,缺少字节顺序标记(尽管属性设置为 true),并且 XML 编辑器将文档拒绝为无效的 UTF-16,因为缺少 BOM。
我在看什么?
'' # Create and load a DOMDocument object.
Dim xmlDoc As New DOMDocument60
xmlDoc.loadXML("<doc><one>test1</one><two>test2</two></doc>")
'' # Set properties on the XML writer - including BOM, XML declaration and encoding
Dim wrt As New MXXMLWriter60
wrt.byteOrderMark = True
wrt.omitXMLDeclaration = False
wrt.encoding = "UTF-16"
wrt.indent = False
'' # Set the XML writer to the SAX content handler.
Dim rdr As New SAXXMLReader60
Set rdr.contentHandler = wrt
Set rdr.dtdHandler = wrt
Set rdr.errorHandler = wrt
rdr.putProperty "http://xml.org/sax/properties/lexical-handler", wrt
rdr.putProperty "http://xml.org/sax/properties/declaration-handler", wrt
'' # Now pass the DOM through the SAX handler, and it will call the writer
rdr.parse xmlDoc
'' # Let the writer do its thing
Dim iFileNo As Integer
iFileNo = FreeFile
Open App.Path + "\saved.xml" For Output As #iFileNo
Print #iFileNo, wrt.output
Close #iFileNo
输出如下所示:
<?xml version="1.0" encoding="UTF-16" standalone="no"?>
<doc><one>test1</one><two>test2</two></doc>
为什么我使用 VB6?它实际上是在 VBA(同一代,VB6 的小子集)中,用作 EMC-Captiva 的 InputAccel/FormWare 的脚本语言,因此不能切换。