xml being generated with encoding="utf-16"

Asked

Viewed 89 times

0

I’m having trouble serializing an xml, the same is being generated with encoding="utf-16".

But the xsd is with encoding="utf-8", how I make 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();
    }
}
  • I don’t get it, he got like this:

  • How is the class structure consulta and the value you are assigning to xmlConsulta?

  • See this http://www.csharp411.com/how-to-force-xmlwriter-or-xmltextwriter-to-use-encoding-other-than-utf-16/

  • opa, thanks get with the link above.

  • I edited the answer, presenting this solution. :)

1 answer

2


This happens because of StringWriter which uses as standard the Enconding UTF-16. One is to make your own implementation solution, inheriting from 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 that 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

  • good afternoon, I tried but it’s still coming out as utf16.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.