3

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?

Freddie Bell
  • 2,186
  • 24
  • 43

1 Answers1

7

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks to other postings on SO, I discovered that the problem is because of the `Memo1.Text` which is UFT-16. By changing the last line to `XMLDoc.SaveToStream(MyStream)`, where `MyStream := TFileStream.Create('test.XML', fmCreate or fmOpenWrite);` the utf-8 indicator is included in the resulting file. Yay. – Freddie Bell Oct 25 '13 at 13:22