如何将 XML 中的编码强制转换为 UTF-8?

How to force encoding in XML to UTF-8?

我正在尝试在 xml 中强制编码,我正在按照以下方式构建:

XmlWriterSettings       xmlSetting = new XmlWriterSettings();
XmlWriter               xmlWriter;
Str                     res;


xmlSetting.encoding ('UTF-8');
xmlWriter = XmlWriter::newXml(xmlSetting);    
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('root');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
xmlWriter.flush();
res = xmlWriter.writeToString();    
info(res);

但是在我的系统中这个结果是:

<?xml version="1.0" encoding="utf-16"?><root />

强制编码为 UTF-8 的正确方法是什么,是否可行

文档未提供示例: https://docs.microsoft.com/en-us/previous-versions/dynamics/ax-2012/system-classes/gg929065(v%3dax.60)

如果您要写入字符串,则编码将被 UTF-16 覆盖。 字符串始终是 Unicode,即 UTF-16。无法使用 writeToString 方法编写任何其他编码。 如果您写入文件,那么您的编码将生效。

XmlWriterSettings       xmlSetting = new XmlWriterSettings();
XmlWriter               xmlWriter;
Str                     res;


xmlSetting.encoding ('UTF-8');

xmlWriter = XMLWriter::newFile(@"C:\TEMP\test.xml", xmlSetting);    
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('root');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
xmlWriter.flush();