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

10.2k Views Asked by At

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?

2

There are 2 best solutions below

1
On

After generate Xml File Make Format and save it will save as UTF8

     Procedure FormatXMLFile(const XmlFile:string);
var
   oXml : IXMLDocument;
 begin
   oXml := TXMLDocument.Create(nil);
   oXml.LoadFromFile(XmlFile);
   oXml.XML.Text:=Xml. xmlDoc.FormatXMLData(oXml.XML.Text);
   oXml.Active := true;
   oXml.SaveToFile(XmlFile);
 end;
1
On

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.