Linked Questions

Popular Questions

XDocument adds carriage return when generating final xml string

Asked by At

I have a case where I would like to generate xml prior to posting it to an API, containing line breaks (\n) but not carriage returns (no \r).

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

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

// inputXmlString: <root>Some text without carriage return\nthis is the new line</root>

var doc = XDocument.Parse(inputXmlString);

var xmlString = doc.Root.ToString();

// xmlString: <root>Some text without carriage return\n\rthis is the new line</root>

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).

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.

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.

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

Related Questions