How do I get encoding = "utf-8"?> in a txmldocument.xml?

Freddie Bell picture Freddie Bell · Oct 24, 2013 · Viewed 8.9k times · Source

This doesn't work for me in Delphi XE2.

Var
  XMLDoc : IXMLDOCUMENT;
begin
  XMLDoc := NewXMLDocument;
  XMLDoc.Active := True;
  XMLDoc.Version := '1.0';
  XMLDoc.Encoding := 'utf-8';
  XMLDoc.Options := [doNodeAutoIndent];
  Memo1.Text := XMLDoc.XML.Text;

I still do NOT get the encoding="utf-8"?> in the resulting doc. But if I say

  XMLDoc.Encoding := 'utf-16';

then it I do get encoding="utf-16"?> in the resulting doc.

Any ideas? Anyone?

Answer

Remy Lebeau picture Remy Lebeau · Oct 24, 2013

UTF-8 is XML's default encoding when no encoding attribute or BOM are present to indicate a different encoding is being used. The underlying XML engine knows that, so it will omit generating an encoding attribute for UTF-8 when it knows it is safe to do so.

AFAIK, there is no way to force IXMLDocument.XML.Text or IXMLDocument.SaveToXML(var XML: DOMString) or IXMLDocument.SaveToXML(var XML: WideString) to generate an encoding attribute for UTF-8. However, IXMLDocument.SaveToXML(var XML: UTF8String) and IXMLDocument.SaveToStream() do generate an encoding attribute for UTF-8.