Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

XElement converts \r\n to \n

I know there is already a question about this: Why XElement Value property changing \r\n to \n?, but the question here was that XElement converts \r\n into \n.

My situation is a bit different, I store \n in my XML, but if I save the XML to a file or a file stream, I get the \r\n back again (Only in the file). Reading it returns \n.

Attached is small snippet of code to see the result. I can understand that due to https://www.w3schools.com/Xml/xml_syntax.asp, \r\n is converted to \n when writing, but I see no reason why it is written as \r\n to the stream or file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System.Xml.Linq;

var text = "Test1" + Environment.NewLine + "Test2" + Environment.NewLine + "Test3";

using MemoryStream stream = new();

var xmlSource = new XElement("Data", text.Replace(Environment.NewLine, "\n"));
xmlSource.Save(stream, SaveOptions.None);
stream.Position = 0;

var xmlTarget = XElement.Load(stream);
Console.WriteLine(xmlTarget.Value);

Is there some explanation on the given behavior?

>Solution :

Well, actually… you can use \r\n or \n in an XML document but a conformant XML parser will normalize either of them to just \n when it reads the document. And usually those line-ending characters are just so that people can read the document more easily, the application which uses the documents normally ignore them. So you’ve only got a serious problem if the application which uses the document is rejecting or mishandling it.

However, yeah, it’s nice for people to be able to read an XML document sometimes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading