Is the XmlSerializer unreliable or am I doing something wrong?

If you run this code:

public class Program { public class MyClass { public string Text { get; set; } } static MyClass myClass = new MyClass(); static string Desktop = "C:\\Users\\Juan Luis\\Desktop\\"; static void Main(string[] args) { myClass.Text = "\r\nhello"; Console.WriteLine((int)myClass.Text[0]); Save(Desktop + "file.xml", myClass); myClass = Load(Desktop + "file.xml"); Console.WriteLine((int)myClass.Text[0]); Console.Read(); } private static MyClass Load(string fileName) { MyClass result = null; using (Stream stream = File.Open(fileName, FileMode.Open)) { XmlSerializer xmlFormatter = new XmlSerializer(typeof(MyClass)); result = (MyClass)xmlFormatter.Deserialize(stream); } return result; } private static void Save(string fileName, MyClass obj) { using (Stream tempFileStream = File.Create(fileName)) { XmlSerializer xmlFormatter = new XmlSerializer(typeof(MyClass)); xmlFormatter.Serialize(tempFileStream, obj); } } } 

The output will be 13, 10. XmlSerializer removes the carriage return. This is a problem in my case, because I need to compare strings for equality in a class that is serialized and deserialized, and this causes the two strings to be equal before serialization is unequal after serialization. What would be the best job?

Edit: After reading the answers, this was my decision if it helps anyone:

 public class SafeXmlSerializer : XmlSerializer { public SafeXmlSerializer(Type type) : base(type) { } public new void Serialize(Stream stream, object o) { XmlWriterSettings ws = new XmlWriterSettings(); ws.NewLineHandling = NewLineHandling.Entitize; using (XmlWriter xmlWriter = XmlWriter.Create(stream, ws)) { base.Serialize(xmlWriter, o); } } } 
+4
source share
1 answer

I would not call it untrustworthy: XmlSerializer allocates empty space around the text inside the elements. If this were not done, the value of the XML documents would change according to how you formatted them in the IDE.

You might consider placing text in a CDATA section that will accurately preserve content. For example, How do you serialize a string as CDATA using XmlSerializer?

Edit:. This will help to better explain where the problem is, as well as a simpler solution - How to keep the XmlSerializer from killing NewLines in strings?

+4
source

Source: https://habr.com/ru/post/1334536/


All Articles