Specify encoding XmlSerializer

c#, c#-4.0, export-to-xml, xml

Solution

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.

Problem

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> ```

Original source

Related problems