Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify encoding XmlSerializer

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>
like image 749
Gandarez Avatar asked Jan 08 '14 13:01

Gandarez


1 Answers

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.

like image 141
Keeler Avatar answered Oct 26 '22 09:10

Keeler