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.
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?
CodePudding user response:
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.