xml being generated with encoding="utf-16"

0

I'm having trouble serializing an xml, it's being generated with encoding="utf-16" .

But xsd is with encoding="utf-8" , how do I get it to be generated with utf-8 ?

var xml = string.Empty;
var serialize = new XmlSerializer(typeof(Consulta));
using (var strignWriter = new StringWriter())
{
    using (var xmlWriter = XmlWriter.Create(strignWriter, new XmlWriterSettings { Indent = true }))
    {
        serialize.Serialize(xmlWriter, xmlConsulta);
        xml = strignWriter.ToString();
    }
}
    
asked by anonymous 28.09.2018 / 16:10

1 answer

2

This happens because of the StringWriter that the UTF-16 Enconding defaults to. One is to do its own implementation by inheriting from the StringWriter and forcing the use of UTF-8

public class StringWriterWithEncoding : StringWriter 
{ 
    public StringWriterWithEncoding( StringBuilder sb, Encoding encoding ) 
        : base( sb ) 
    { 
        this.m_Encoding = encoding; 
    } 
    private readonly Encoding m_Encoding; 
    public override Encoding Encoding 
    { 
        get
        { 
            return this.m_Encoding; 
        } 
    } 
} 

And then make the change in your code to work with this implementation.

string xml = string.Empty;
var serialize = new XmlSerializer(typeof(Consulta));

using (var strignWriter = new StringWriterWithEncoding(new StringBuilder(),UTF8Encoding.UTF8))
{       
    using (var xmlWriter = XmlWriter.Create(strignWriter, new XmlWriterSettings { Indent = true }))
    {
        serialize.Serialize(xmlWriter, xmlConsulta);
        xml = strignWriter.GetStringBuilder().ToString();
    }
}

Source >

    
28.09.2018 / 17:22