When I use XmlReader.ReadOuterXml(), elements are separated by \\n instead of \\r\\n. So, for example, if I have XmlDocument representatino of
<
I had to write database data to an xml file and read it back from the xml file, using LINQ to XML. Some fields in a record were themselves xml strings complete with \r characters. These had to remain intact. I spent days trying to find something that would work, but it seems Microsoft was by design converting \r to \n.
The following solution works for me:
To write a loaded XDocument to the XML file keeping \r intact, where xDoc is an XDocument and filePath is a string:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{ NewLineHandling = NewLineHandling.None, Indent = true };
using (XmlWriter xmlWriter = XmlWriter.Create(filePath, xmlWriterSettings))
{
xDoc.Save(xmlWriter);
xmlWriter.Flush();
}
To read an XML file into an XElement keeping \r intact:
using (XmlTextReader xmlTextReader = new XmlTextReader(filePath)
{ WhitespaceHandling = WhitespaceHandling.Significant })
{
xmlTextReader.MoveToContent();
xDatabaseElement = XElement.Load(xmlTextReader);
}