I have got the following exception from the below code block.
An error occurred while parsing EntityName. Line1, position 844.
I was trying
This has already been answered, but found a nicer way of achieving the same outcome by doing this in .NET 4.5 by using the Escape method as below:
var xmlWithEscapedCharacters = SecurityElement.Escape(xmlWithoutEscapedCharacters);
and then just plug that string into the XML that is being generated.
Link: MSDN - SecurityElement.Escape Method