XML serialization invalid character

866 views Asked by At

I'm getting the following error

Hexadecimal value 0x02, is an invalid character

when I'm generating the XML document

using MemoryStream ms = new();
var XML = new XmlSerializer(typeof(InvoiceType));
var encoding = Encoding.UTF8;

using (StreamWriter sw = new StreamWriter(ms, encoding))
{
    XML.Serialize(sw, doc, namespace);
}

return ms.ToArray();

The exception is thrown from the Serialize() method; I tried to encode it but it didn't solve the issue, I also tried to encode the string that caused the error before passing it to the document but with no luck

Can you please help me with this one?

1

There are 1 answers

0
vega_gf On

I resolved this issue by sanitizing the source of error (customer input) using this method

public static string RemoveInvalidXmlChars(string content)
{
     return  new string(content.Where(ch =>System.Xml.XmlConvert.IsXmlChar(ch)).ToArray());
}

credit to @Alex Vazhev

link