Keep ‘\r\n’ in XML Serialization and Deserializtion in C#

The following example shows to keep the \r\n characters in the string after Serialization and Deserializtion.

Generally when you serialize an object with a string value that contains ‘\r\n\’ (Carriage Return and new line characters in string) and after deserialize it than in the outcome ‘\r’ is disappeared. Suppose if you string is ‘5 Avenue \r\n North road’, the string comes after deserialize as ‘5 Avenue \n North road’.

Let’s suppose the following class is need to Serialize and Deserialize.

public class clsTest
{
    public  string strQuery = "";
}

The following function serialize the string that contains ‘\r\n’.

private void SerializationAndDeserialize()
    {
        XmlSerializer ser = new XmlSerializer(typeof(clsTest));
        clsTest s = new clsTest();
        s.strQuery = "5 Avenue \r\n North road";
        StringWriter w = new StringWriter();
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.NewLineHandling = NewLineHandling.Entitize;
 
        using (XmlWriter wr = XmlWriter.Create(w, ws))
        {
            ser.Serialize(wr, s);
        }
 
        string serilizeString = w.GetStringBuilder().ToString();
 
        clsTest s2 = (clsTest)ser.Deserialize(new StringReader(serilizeString));
 
        string deselizeString=s2.strQuery;
 
}

You’ll find the same value in the string variable serilizeString and deselizeString.

Glossery

Serialization: Serialization is the way to convert an object into a stream of bytes that can be store or transmit into memory, a database, or a file like XML.

In the .Net there is the Environment.NewLine method that provide the correct representation according to an Operating Systems.

In your project it may be very useful and this is easy to use because .net framework has several c# serialization techniques such as : XML serialization, Binary serialization and SOAP serialization.In the above example I am using the XML serialization to convert the instance of the class ‘ ‘.

\n and \r characters:

Basically \n and \r escape characters are used for the new line representation. This depends on the operation systems

\r: Multics, Unix and Unix-like systems (GNU/Linux, FreeBSD,OS X, Xenix, AIX, etc.),Amiga, RISC OS, BeOS and others.
\n: Commodore 8-bit machines, ZX Spectrum,,Acorn BBC,Apple II family, TRS-80, Mac OS.
\n\r: Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC

Unicode representation:

LF: Line Feed, U+000A
CR: Carriage Return, U+000D
CR+LF: CR (U+000D) followed by LF (U+000A)

In the .Net there is the Environment.NewLine method that provide the correct representation according to an Operating Systems.