views:

978

answers:

3

The following VBA code generates <?xml version="1.0"?> as output.

Dim XML As New DomDocument 
Dim pi As IXMLDOMProcessingInstruction

'.... some code that sets the root element of the document

Set pi = XML.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")
        XML.insertBefore pi, XML.documentElement

Why is the encoding="UTF-8" left out?

A: 

UTF-8 is the default encoding anyway. What you've specified is redundant, so the serializer likely omits it. The version field is not an optional field, though. If the file has an XML declaration at all, the declaration must include the version field.

Rob Kennedy
version is also default. still it's in the output.
norbertB
Um, thanks for accepting my answer, but I'm inclined to think Bobince's is the better one. Apparently, despite looking just like a processing instruction, <?xml isn't one, so don't use createProcessingInstruction for that.
Rob Kennedy
+2  A: 

<?xml?> is not a Processing Instruction. The <?xml?> construct is called the XML declaration and obeys different rules to a real Processing Instruction. Creating a PI with name ‘xml’ is not well-formed; names beginning with ‘xml’ are reserved.

To change the format of the prolog you need to configure an XMLWriter, setting ‘version’, ‘encoding’ or simply ‘omitXMLDeclaration’ to remove it altogether, which is perfectly fine since 1.0 and UTF-8 are the default values.

bobince
A: 

The encoding is missing for a reason.

Short story:

  • when you save() the document, the encoding is written correctly
  • when you look at the XML property, you will always get a Unicode string, no matter what encoding you have specified (all strings in VBA are Unicode). That means:
    • there is no encoding attribute, Unicode is assumed by default
    • you can feed the property value directly to LoadXML() without getting this error message: "Switch from current encoding to specified encoding not supported."

Long story: Chris Lovett "How to Encode XML Data"

Tomalak