To create an encoding like encoding="windows-...">

XML serialization and coding

I need xml encoding:

<?xml version="1.0" encoding="windows-1252"?> 

To create an encoding like encoding="windows-1252" , I wrote this code.

 var myns = OS.xmlns; using (var stringWriter = new StringWriter()) { var settings = new XmlWriterSettings { Encoding = Encoding.GetEncoding(1252), OmitXmlDeclaration = false }; using (var writer = XmlWriter.Create(stringWriter, settings)) { var ns = new XmlSerializerNamespaces(); ns.Add(string.Empty, myns); var xmlSerializer = new XmlSerializer(OS.GetType(), myns); xmlSerializer.Serialize(writer, OS,ns); } xmlString= stringWriter.ToString(); } 

But I'm still not getting the expected encoding, what am I missing? Please direct me to generate encoding like encoding="windows-1252"? . What do I need to change in my code?

+7
source share
1 answer

As long as you output XML directly to String (via StringBuilder or StringWriter ), you will always get UTF-8 or UTF-16. This is because strings in .NET are represented as Unicode characters .

To get the correct encoding, you have to switch to binary output , for example Stream .

Here is an example:

 var settings = new XmlWriterSettings { Encoding = Encoding.GetEncoding(1252) }; using (var buffer = new MemoryStream()) { using (var writer = XmlWriter.Create(buffer, settings)) { writer.WriteRaw("<sample></sample>"); } buffer.Position = 0; using (var reader = new StreamReader(buffer)) { Console.WriteLine(reader.ReadToEnd()); Console.Read(); } } 

Related Resources:

+8
source

All Articles