Search code examples
xmlencodingaxaptadynamics-ax-2012-r3

How to force encoding in XML to UTF-8?


I am trying to enforce encoding in the xml I am building in following way:

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);

But the result of this in my system is:

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

What is the proper way to force encoding to UTF-8 and is it possible

Documentation does not provides examples: https://learn.microsoft.com/en-us/previous-versions/dynamics/ax-2012/system-classes/gg929065(v%3dax.60)


Solution

  • If you're writing to a string, then the encoding will be overridden by UTF-16. Strings are always Unicode, that is, UTF-16. There is no way to write any other encoding using writeToString method. If you write to file, then your encoding will take effect.

    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();
    

    enter image description here