Home / Blog / Remove illegal characters from xml
Remove illegal characters from xml

Remove illegal characters from xml

If the exception 'System.ArgumentException: hexadecimal value is an invalid character' is raised while reading or writing xml make sure the xml contains no illegal characters

You can strip these illegal characters with this method.

private static string StripIllegalXmlChars(string s)
{
	if (string.IsNullOrEmpty(s))
		return string.Empty;

	StringBuilder output = new StringBuilder(s.Length, s.Length);
	char current;
	char[] charArray = s.ToCharArray();
	for (int i = 0; i < charArray.Length; i++)
	{
		current = charArray[i];
		if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) ||
		((current >= 0xE000) && (current <= 0xFFFD)) ||
		((current >= 0x10000) && (current <= 0x10FFFF)))
			output.Append(current);
	}
	return output.ToString();
}

Contact