我在"How to make XMLDOMDocument include the XML Declaration?"中看到的代码上使用了一个变体(也可以在MSDN看到。如果我将编码更改为“UTF-16”,我们会认为它会输出为UTF -16 ...并且“通过”查看文本编辑器中的输出来“确实”...但是在十六进制编辑器中检查它,缺少字节顺序标记(尽管属性设置为true)和XML对于缺少的BOM,编辑拒绝该文档为无效的UTF-16。
我在俯瞰什么?
'' # 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的脚本语言,因此切换不是一种选择。
答案 0 :(得分:2)
问题是当你从writer的输出属性中检索一个值时,你会得到一个字符串。因为VB中的字符串总是UTF-16,所以无论编码如何都是你得到的。由于VB中的字符串总是UTF-16,因此不存在需要BOM的概念,因此也不包括。
编码和BOM属性仅影响当IStream的实现分配到输出属性时编写器将如何编写XML。
尝试修改解析调用的代码,如下所示: -
Dim oStream As ADODB.Stream
Set oStream = New ADODB.Stream
oStream.Open
oStream.Type = adTypeBinary
wrt.output = oStream
rdr.parse xmlDoc
oStream.SaveToFile App.Path + "\saved.xml"
oStream.Close
这应该会产生所需的输出。