-2

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?

Community
  • 1
  • 1

2 Answers2

3

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.

This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

To preserve your newlines, you'll have to do some encoding, or simply change all of your \n back to \r after deserialization

Community
  • 1
  • 1
caesay
  • 16,932
  • 15
  • 95
  • 160
-1

It is not the serializer who does this but an XmlWriter that is created for you inside of the Serialize method. You can have more control over the settings of this writer if you create it by yourself providing it the XmlWritterSettings object and then pass this writter to the Serialize method instead of the stream like you do right now. Google XmlWitterSettings.

Trident D'Gao
  • 18,973
  • 19
  • 95
  • 159
  • Well, this is wrong for certain, the serialized files have CRLF in the file, when unserialized they are just LF. – Jay Croghan Dec 13 '20 at 08:00