Possible Duplicate:
XML Carriage return encoding
I have a class with some simple string and int values on it that I am using the XmlSerializer to serialize to a file like so. (this is literally the code I am using)
XmlSerializer xmlser = new XmlSerializer(typeof(NPC));
using (Stream st = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlser.Serialize(st, npc);
}
That all works fine; I have verified that upon serialization, the correct data is in the file in the <Other></Other> element, complete with \r\n, if I entered such in the file. The problem comes upon deserialization (again; literally the code I am using, except for the ‘test’ result upon failure)
XmlSerializer xmlser = new XmlSerializer(typeof(NPC));
NPC npc = null;
using (Stream st = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
npc = (NPC)xmlser.Deserialize(st);
}
//Testing...
if(!npc.Other.Contains("\r\n"))
{
//this always occurs, even when the <Other></Other> item DOES have CR-LF
}
Immediately upon deserialization, string properties on the object which had \r\n values will have them replaced by \n alone. I have verified even after deserializing that the file reflects \r\n in the proper elements, and I am doing nothing else with the npc object before testing that the \r are removed.
NPC is a simple class, defined like so:
[Serializable]
public class NPC
{
public int Field1{get; set;}
public string Other {get; set;}
public int Etc... {get; set;}
}
So; why is my Other property losing its \r from its \r\n upon deserialization?
Here is a link you can look at:
XML Carriage return encoding
If you google “XML Carriage Return” you will come up with many many other links to people with the same problem.
It would appear that this is by design.
To preserve your newlines, you’ll have to do some encoding, or simply change all of your
\nback to\rafter deserialization