Specify encoding XmlSerializer

46.3k views Asked by At

I've a class correctly defined and after serialize it to XML I'm getting no encoding.

How can I define encoding "ISO-8859-1"?

Here's a sample code

var xml = new XmlSerializer(typeof(Transacao));
var file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml"),FileMode.OpenOrCreate);            
xml.Serialize(file, transacao);            
file.Close();

Here are the beginning of xml generated

<?xml version="1.0"?>
<requisicao-transacao xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <dados-ec>
    <numero>1048664497</numero>
2

There are 2 answers

0
Keeler On BEST ANSWER

The following should work:

var xml = new XmlSerializer(typeof(Transacao));

var fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml");
var appendMode = false;
var encoding = Encoding.GetEncoding("ISO-8859-1");

using(StreamWriter sw = new StreamWriter(fname, appendMode, encoding))
{
    xml.Serialize(sw, transacao);
}

If you don't mind me asking, why do you need ISO-8859-1 encoding in particular? You could probably use UTF-8 or UTF-16 (they're more commonly recognizable) and get away with it.

0
cacau On

Create a StreamWriter with the desired encoding:

System.Text.Encoding code = *WhateverYouWant*
StreamWriter sw = new StreamWriter(file, code);