XslCompiledTransform uses UTF-16 encoding

I have the following code that I want to output XML data using the UTF-8 encoding format. but it always outputs data in UTF-16:

XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(XmlReader.Create(new StringReader(xsltString), new XmlReaderSettings())); StringBuilder sb = new StringBuilder(); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.Encoding = Encoding.UTF8; writerSettings.Indent = true; xslt.Transform(XmlReader.Create(new StringReader(inputXMLToTransform)), XmlWriter.Create(sb, writerSettings)); 
+7
source share
2 answers

The XML output will contain a header based on the encoding of the stream, not the encoding specified in the settings. Since the strings are 16-bit Unicode, the encoding will be UTF-16. The workaround is to suppress the header and add it yourself:

 writerSettings.OmitXmlDeclaration = true; 

Then, when you get the result from StringBuilder:

 string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + sb.ToString(); 
+10
source

If a MemoryStream used instead of a StringBuilder , the XmlWriter will abide by the encoding specified in the XmlWriterSettings , since the MemoryStream does not have a built-in encoding such as StringBuilder does.

+7
source

All Articles