0

I want to produce an XML file where carriage return in elements are represented by the following sequence 
 but I'm unable get:

<elem>Hello&#13;world!</elem>

If I do the following:

var elem = new XElement("elem", "Hello\nworld!");

It produces:

<elem>Hello
world!</elem>

If I do the following:

var elem = new XElement("elem", "Hello&#13;world!");

It produces:

<elem>Hello&amp;#13;world!</elem>

Any ideas?

Martin Delille
  • 11,360
  • 15
  • 65
  • 132
  • 1
    possible duplicate of [What's the correct way to encode CR-LF line breaks in text/xml values?](http://stackoverflow.com/questions/15016004/whats-the-correct-way-to-encode-cr-lf-line-breaks-in-text-xml-values) – crthompson Oct 16 '14 at 18:48
  • @JustinRusso There was a mistake in my formatting but as you can see ` ` produces `&#13;` – Martin Delille Oct 17 '14 at 08:34
  • @paqogomez It doesn't provide interesting information. In my case the expected string is `Hello world` – Martin Delille Oct 17 '14 at 08:36
  • `var elem = new XElement("elem", "Hello world!"); Console.WriteLine(elem.Value); Console.WriteLine(elem);` gives me `Hello world!Hello&#13;world! ` which means that the value of elem is stored as you asked, isn't it ? – Thomas Ayoub Oct 17 '14 at 10:43
  • In fact I want it in the file, but I find a way of using the XDocument.ToString() method – Martin Delille Oct 17 '14 at 10:56
  • Since my answer is the actual answer to your question, can you mark it as the "Answer?" Thanks. Justin – Justin Russo Mar 12 '15 at 13:41

1 Answers1

1

Okay your answer is pretty clear. Anytime you need to write special chars into xml values, you would use CDATA.

Here's how you do it.

<elem><![CDATA[Hello&#13;world!]]></elem>

This is the fix you are looking for.

[UPDATE] The only reason I stumbled on this answer initially, was because I was thinking about HTML. However, if you were writing this in HTML, you would simply use a <br /> tag.

Justin Russo
  • 2,214
  • 1
  • 22
  • 26