C#C
C#3y ago
Chik3r

✅ Serializing XML with diacritics/accents

Hi, I'm trying to serialize a class to xml that contains some strings, some of which may contain an accent (example:
genérica
) or other latin characters (example:
diseño
). Currently I'm serializing it using the following code:
private static byte[] SerializeXml<T>(T data) {
    using MemoryStream mem = new();
    using StreamWriter writer = new(mem);
    // XmlWriterSettings settings = new() {Encoding = Encoding.Default};
    
    XmlSerializer serializer = new(typeof(T));
    // using StringWriter writer = new Utf8StringWriter();
    using XmlWriter xmlWriter = XmlWriter.Create(writer);
    serializer.Serialize(xmlWriter, data);
    return mem.ToArray();
}

(I was previously trying to use a StringWriter but it also doesn't work)
It ends up replacing the characters with
??
instead of writing the actual characters.
The final XML needs to be formatted to UTF8 (and include
encoding="utf-8"
at the top of the xml), so I'm not able to use iso-8859-1 (but even when I tried to use it as an encoding it replaced characters with "??")
Was this page helpful?