XDocument adds carriage return when generating final xml string
XNode.ToString
is a convenience that uses an XmlWriter
under the covers - you can see the code in the reference source.
Per the documentation for XmlWriterSettings.NewLineHandling
:
The Replace setting tells the XmlWriter to replace new line characters with \r\n, which is the new line format used by the Microsoft Windows operating system. This helps to ensure that the file can be correctly displayed by the Notepad or Microsoft Word applications. This setting also replaces new lines in attributes with character entities to preserve the characters. This is the default value.
So this is why you're seeing this when you convert your element back to a string. If you want to change this behaviour, you'll have to create your own XmlWriter
with your own XmlWriterSettings
:
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
NewLineHandling = NewLineHandling.None
};
string xmlString;
using (var sw = new StringWriter())
{
using (var xw = XmlWriter.Create(sw, settings))
{
doc.Root.WriteTo(xw);
}
xmlString = sw.ToString();
}
Have you tried:
how to remove carriage returns, newlines, spaces from a string
string result = XElement.Parse(input).ToString(SaveOptions.DisableFormatting);
Console.WriteLine(result);