I am trying to set encoding type to ISO-8859-1 while serializing an object. The code runs without throwing any exception but the returned coding type is always set to "UTF-16". I have searched many examples, there are 100s of samples, but I am simply unable to force the desired encoding type.
My questions is that how can I force it to set encoding to ISO-8859-1?
Thanks in advance.
The code is:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = false,
Encoding = Encoding.GetEncoding("ISO-8859-1")
};
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, obj, ns);
}
return stringWriter.ToString();
}
When you write XML to a TextWriter
(e.g. StringWriter
, StreamWriter
), it always uses the encoding specified by the TextWriter
, and ignores the one specified in XmlWriterSettings
. For StringWriter
, the encoding is always UTF-16, because that's the encoding used by .NET strings in memory.
The workaround is to write to a MemoryStream
and read the string from there:
var encoding = Encoding.GetEncoding("ISO-8859-1");
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = false,
Encoding = encoding
};
using (var stream = new MemoryStream())
{
using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, obj, ns);
}
return encoding.GetString(stream.ToArray());
}
Note that if you have the XML in a string, when you write it to a file you need to make sure to write it with the same encoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With