8

i want the xml encoding to be:

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

To generate 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 am still not getting my expected encoding what am I missing? Please guide me to generate encoding like encoding="windows-1252"?. What do I need to change in my code?

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154
Mou
  • 15,673
  • 43
  • 156
  • 275

1 Answers1

9

As long as you output the XML directly to a String (through a StringBuilder or a StringWriter) you'll always get UTF-8 or UTF-16 encondings. This is because strings in .NET are internally represented as Unicode characters.

In order to get the proper encoding you'll have to switch to a binary output, such as a Stream.

Here's a quick 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:

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154