Specify XmlSerializer Encoding

I correctly defined the class and after serializing it to XML I do not get any encoding.

How can I determine the encoding "ISO-8859-1"?

Here is 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 is the beginning of the created xml

 <?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> 
+8
c # xml
source share
2 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 do not mind, I ask, why do you need to code ISO-8859-1 in particular? You could probably use UTF-8 or UTF-16 (they are more recognizable) and leave with it.

+16
source share

Create a StreamWriter with the desired encoding:

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

All Articles