DZN
DZN

Reputation: 1553

Why is there no "encoding" attribute in a string got by "IXMLDocument.SaveToXML" method?

I use NewXMLDocument() to produce an XML document of my data.

There is a SaveToXML() method to save the document to an XML-formatted string variable.

The problem is that the XML string does not contain an "encoding" attribute in the head tag.

But, if we save the XML document to a file with the SaveToFile() method, the "encoding" attribute will exist in it.

Here is my code:

var
  XML: IXMLDocument;
  RootNode, CurNode: IXMLNode;
  XmlString: string;
begin
  XML := NewXMLDocument;
  XML.Encoding := 'utf-8';
  XML.Options := [doNodeAutoIndent];
  RootNode := XML.AddChild('XML');
  CurNode := RootNode.AddChild('List');
  CurNode := CertList.AddChild('Item');
  CurNode.Text := 'bla-bla-bla';
  ...

  XMl.SaveToXML(XmlString);  // <<--- no "encoding" attribute here

  XMl.SaveToFile('my-list.xml');
  XMl := nil;
end;

Is there a way to make the SaveToXML() method add the "encoding" attribute?

Upvotes: 2

Views: 635

Answers (1)

kobik
kobik

Reputation: 21242

You need to use the overload method IXMLDocument.SaveToXML(var XML: UTF8String).
That will encode the xml to UTF-8 and add the encoding attribute in the xml header.
Declare your XmlString as UTF8String to get the desired result.

When you declare XmlString as string like you did, which is UTF-16 (Unicode) in Delphi 2009+, you actually call SaveToXML(var XML: DOMString). The DOMString is defined as UnicodeString.
By default, variables declared as type string are UnicodeString. The output xml is UTF-16 and the encoding attribute is omitted.

Upvotes: 2

Related Questions