1

I had this code to create an xml. It used to work as expected, but in the first xml row, the encoding was set as utf-16.

The code was:

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

    using (StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

Since I need to encode it in UTF-8, I edit it as follows:

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());


    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new  UTF8Encoding(),
        Indent = false,
        OmitXmlDeclaration = false
    };

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            xmlSerializer.Serialize(xmlWriter, toSerialize);
        }
        return textWriter.ToString();
    }
}

The code seems good, but the generated xml has still the row

<?xml version="1.0" encoding="utf-16"?>

and not

<?xml version="1.0" encoding="utf-8"?>

Why? How can I create an utf-8 xml?

dbc
  • 104,963
  • 20
  • 228
  • 340
Piero Alberto
  • 3,823
  • 6
  • 56
  • 108
  • Possible duplicate of [Serializing an object as UTF-8 XML in .NET](https://stackoverflow.com/questions/3862063/serializing-an-object-as-utf-8-xml-in-net) – dbc Apr 06 '18 at 22:06
  • Since you want to write to a string using a `StringWriter`, the specific answer you want from [Serializing an object as UTF-8 XML in .NET](https://stackoverflow.com/questions/3862063/serializing-an-object-as-utf-8-xml-in-net) is [this one by Jon Skeet](https://stackoverflow.com/a/3862106/3744182). See also [this answer](https://stackoverflow.com/a/1564727/3744182) and [this one](https://stackoverflow.com/a/955698/3744182). – dbc Apr 06 '18 at 22:07

0 Answers0