Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml serialization and encoding

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?

like image 857
Mou Avatar asked May 09 '11 07:05

Mou


1 Answers

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:

  • C# in Depth: Strings in C# and .NET
like image 118
Enrico Campidoglio Avatar answered Nov 08 '22 03:11

Enrico Campidoglio