Invalid XML encoding tag written by WriteStartDocument

I installed XMLWriter to use UTF8 encoding, but the WriteStartDocument method still writes the UTF16 tag.

This is part of the code:

m_sbXML = New System.Text.StringBuilder m_xmlWriterSettings = New System.Xml.XmlWriterSettings With m_xmlWriterSettings .Indent = True .IndentChars = " " .Encoding = System.Text.Encoding.UTF8 End With m_xmlWriter = System.Xml.XmlWriter.Create(m_sbXML, m_xmlWriterSettings) Call m_xmlWriter.WriteStartDocument() 

He should write a document tag:

 <?xml version="1.0" encoding="utf-8"?> 

but instead he writes:

 <?xml version="1.0" encoding="utf-16"?> 
+4
source share
1 answer

You are writing StringBuilder . Strings in .NET are always encoded in UTF-16 encoding.

If you want to create an XML file encoded in UTF-8, write Stream .

Example:

 var settings = new XmlWriterSettings { Indent = True, IndentChars = " ", Encoding = Encoding.UTF8 }; using (var stream = new MemoryStream()) using (var writer = XmlWriter.Create(stream, settings)) { writer.WriteStartDocument(); // ... } 
+3
source

Source: https://habr.com/ru/post/1387527/


All Articles