Search code examples
c#xmlserializationdeserializationnewline

Don't understand why newlines are getting lost after XML Serialization


From my browser, I send the following payload as a string,

<Form>
<Field Sql="select top(1) 
Row
FROM 
Table">
</Field>
</Form>

Notice how the value of Sql has newline characters Row, FROM, and Table are all on a new line.

I pass this string XML to the method,

XmlSerializationUtility.FromXml<MyPayload>(xml, "Form")
public static T FromXml<T>(string xml, string root)
{
    XmlSerializer xmlSer = GetXMLSerializer(typeof(T), new XmlRootAttribute(root));
    var stringReader = new StringReader(xml);
    T result = (T)xmlSer.Deserialize(stringReader);

    // Output or inspect the deserialized value
    Console.WriteLine("Deserialized value: " + result?.ToString());

    // Return the deserialized result
    return result;
}
private static XmlSerializer GetXMLSerializer(Type type, XmlRootAttribute root)
{
    string key = string.Format(CultureInfo.InvariantCulture, "CachedXmlSerializer:{0}:{1}", type, root.ElementName);

    bool isCached = _serializers.TryGetValue(key, out XmlSerializer ser);

    if (!isCached)
    {
        ser = new XmlSerializer(type, root);
        _serializers.Add(key, ser);
    }

    return ser;
}

When I inspect my payload after FromXml is executed, all of those newline characters are gone, and I see select top(1) Row FROM Table.

Do you have any idea why I am losing all those newline chars?


Solution

  • XmlSerializer by default has XML normalization turned on and also only returns significant whitespace. If you want to keep the "Sql" as is you need to pass in a XmlTextReader to the Deserialize method like this

    XmlTextReader xmlReader = new XmlTextReader(stringReader);
    xmlReader.Normalization = false;
    T result = (T)xmlSer.Deserialize(xmlReader);