user1731444
user1731444

Reputation: 23

Character encoding, char to xml value

I am trying to convert some characters (\t, \r, \n, "\r\n") to XML compatible "values". So '\t' should be 	 and \r\n would be 
. I have tried using HttpUtility.HtmlEncode(), but without any success.

For those interested:

I wasn't able to get exactly the format I wanted, but the following seems to do the same:

"\r\n".ToList().ForEach(c => Console.Write("&#x" + ((int)c).ToString("X") + ";"));

Upvotes: 2

Views: 313

Answers (1)

Vyktor
Vyktor

Reputation: 20997

AFAIK entities like \t, \r or \n doesn't need to be "xml-escaped" (in fact you cannot escape them by default because it may be just source formatting or it may be real new line and you cannot know which one it is), so best solution I found was to convert those characters "by hand":

HttpUtility.HtmlEncode()
    .Replace("\n\r", "<br/>")
    .Replace("\n", "<br/>")  // Or use &#012; if you want it "binary safe"
    .Replace("\r", "<br/>")
    .Replace("\t", "&#009;");

Upvotes: 2

Related Questions