0

I have this chunk of code:

...
var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };

using (var xmlWriter = XmlWriter.Create(strbuilder, settings))
{
    var serializer = new XmlSerializer(model.GetType());
    Encoding encoding = Encoding.UTF8;
    serializer.Serialize(xmlWriter, model, xmlns, encoding.EncodingName); //this line throw an error
}
...

What Im doing wrong? If I remove encoding object, and let it use just settings object that it has UTF8, for some reason it generates xml with utf16 instead of utf8. How can I fix this?

Stefan0309
  • 1,602
  • 5
  • 23
  • 61
  • XmlWriter and XmlReader can be confusing sometimes with BOMs and their overall syntax. May I point you to this possible solution? Not mine so not submitting as answer: https://stackoverflow.com/a/3862106/2937845 – to11mtm Oct 15 '22 at 18:16
  • Looks like Net updates are now automatically using utf-16 instead of utf-8. Notice this early the weeks. – jdweng Oct 15 '22 at 20:26
  • Would you mind telling us, *which* exception you get? Also: from the valiable names, it seems that you are serializing to a `StringBuilder` - note that strings are always UTF16 in .NET. – Klaus Gütter Oct 16 '22 at 04:54
  • You don't seem to be using the `encodingStyle` argument properly. From the [docs for `XmlSerializer.Serialize(XmlWriter, object, XmlSerializerNamespaces, string encodingStyle)`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer.serialize?view=net-6.0#system-xml-serialization-xmlserializer-serialize(system-xml-xmlwriter-system-object-system-xml-serialization-xmlserializernamespaces-system-string)): ... – dbc Oct 25 '22 at 18:21
  • ... *Set the encodingStyle parameter to `http://schemas.xmlsoap.org/soap/encoding/` for SOAP version 1.1 encoding; otherwise, set it to `http://www.w3.org/2001/12/soap-encoding` for SOAP version 1.2 encoding.* As such this would seem to have nothing to do with string encoding, and `Encoding.EncodingName` should not be passed in here. – dbc Oct 25 '22 at 18:22
  • Anyway you are getting `utf16` instead of `utf8` because you are writing with a `StringWriter` and c# `string` is always encoded as `utf16`. If you were writing to a `Stream` then `XmlWriterSettings.Encoding` would control the encoding. But if you just want to make the XML declaration show utf8 instead of utf16, see [How to put an encoding attribute to xml other that utf-16 with XmlWriter?](https://stackoverflow.com/a/427737), which looks to be a duplicate. – dbc Oct 25 '22 at 18:25

0 Answers0