When I use XmlReader.ReadOuterXml(), elements are separated by \\n instead of \\r\\n. So, for example, if I have XmlDocument representatino of
<
Solution 1: Write entitized XML
Use a well configured XmlWriter
with NewLineHandling.Entitize
option so the XmlReader
will not eliminate normalize the line endings.
You can use such a custom XmlWriter
even with XDocument
:
xDoc.Save(XmlWriter.Create(fileName, new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize }));
Solution 2: Read non-entitized XML without normalization
Solution 1 is the cleaner way; however, it is possible that you already have the non-entitized XML and you cannot modify the creation and still you want to prevent normalization. The accepted answer suggests a replace but that replaces every \n occurrences blindly even if it is not desirable. To retrieve all of the line endings as they are in the file you can try to use the legacy XmlTextReader
class, which does not normalize XML files by default. You can use it with XDocument
, too:
var xDoc = XDocument.Load(new XmlTextReader(fileName));