using System.Text.RegularExpressions;
public static void Main()
string hex = string.Empty;
Console.WriteLine("-------------Example 1-------------------");
hex = GetHexString("©Ø");
string a = @"This" + hex + " "+ hex + "is " + hex + "a " + hex + "text";
a = RemoveTroublesomeCharacters(a);
Console.WriteLine("-------------Example 2-------------------");
a = @"This" + hex + " "+ hex + "is " + hex + "a " + hex + "text";
a = RemoveTroublesomeCharacters(a);
public static string CleanInvalidXmlChars(string text)
string pattern = @"&#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF]);";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
text = regex.Replace(text, string.Empty);
public static string GetHexString(string strToHex)
char [] values = strToHex.ToCharArray();
StringBuilder sb = new StringBuilder();
foreach(char letter in values)
int newValue = Convert.ToInt32(letter);
sb.AppendFormat("0x{0:X2}", newValue);
Console.WriteLine(sb.ToString() + " // This is the hex value for: " + strToHex);
public static string RemoveTroublesomeCharacters(string inString)
if (inString == null) return null;
StringBuilder newString = new StringBuilder();
for (int i = 0; i < inString.Length; i++)
if (XmlConvert.IsXmlChar(ch))
return newString.ToString();