0

A var doc = XDocument.Parse("<r>a\r\nb</r>") and then doc.Root.Value gives me a\n\b instead of the expected a\r\nb. I tried most of the Parse and Load overloads, using XmlReader, Stream, TextReader, but didn't manage to load the \r\n as \r\n; I always get a \n. I'm using .NET 6 on Windows.

There is this question about XElement.Load with an answer suggesting to use LoadOptions.PreserveWhitespace, but this doesn't work for me when using XDocument.Load or XDocument.Parse.

How can I load an XML document containing a \r\n in a value into an XDocument preserving that \r\n?

Martin
  • 1,986
  • 15
  • 32
  • It's simply not compliant to have XML with `\r` in it, you need to encode it. https://dotnetfiddle.net/S5ZC0B – Charlieface Jun 15 '22 at 11:35
  • @Charlieface You are right, thanks! The [End-of-Line Handling](https://www.w3.org/TR/xml/#sec-line-ends) section in the XML spec is the key point. If you post this as answer, I'll mark it as accepted. By the way, as I understand it, it's compliant to have `\r` in XML, but a compliant parser ignores it. – Martin Jun 15 '22 at 12:00
  • You should have a button to accept the above link as a duplicate – Charlieface Jun 15 '22 at 12:04

0 Answers0