XDocument adds carriage return when generating final xml string
<p>I have a case where I would like to generate xml prior to posting it to an API, containing line breaks (<strong>\n</strong>) but not carriage returns (no <strong>\r</strong>).</p>

<p>In C# though, it seems that XDocument automatically adds carriage returns in its to-string method:</p>

<pre><code>var inputXmlString = "&lt;root&gt;Some text without carriage return\nthis is the new line&lt;/root&gt;";

// inputXmlString: &lt;root&gt;Some text without carriage return\nthis is the new line&lt;/root&gt;

var doc = XDocument.Parse(inputXmlString);

var xmlString = doc.Root.ToString();

// xmlString: &lt;root&gt;Some text without carriage return\n\rthis is the new line&lt;/root&gt;
</code></pre>

<p>In doc.Root.ToString(), sets of \n\r are added between elements for indentation which does not matter for the receivers interpretation of the xml message as a whole. However, the ToString() method also adds \r inside the actual text field where I need to preserve standalone line breaks (\n without \r after it).</p>

<p>I know I could do a final string replace, removing all carriage returns from the final string prior to the actual HTTP post to be performed, but this just seems wrong.</p>

<p>The issue is the same when constructing the xml-document using XElement objects instead of Document.Parse. The issue also persists, even if I use a CData element to wrap the text.</p>

<p>Can anyone explain to me, if I do something wrong or if there is some clean way of achieving what I try to do?</p>