在解釋XML時,會因為一些非法字符解析異常,因此在解析XML前處理非法字符十分重要。
XML的非法字符包括:
1.需去除去的非法字符范圍,在W3C手冊XML的非法字符可以查找到:
\\x00-\\x08
\\x0b-\\x0c
\\x0e-\\x1f
2.需要替換的字符:
字符 | HTML字符 | 字符編碼 |
---|---|---|
和 & | & | & |
單引號 ’ | ' | ' |
雙引號 ” | " | " |
大於號 > | > | > |
小於號 < | < | < |
下面程序寫個Demo(C#):
static void Main(string[] args)
{
string str = "Canon \"LCIXUS3< Soft>her\x00 Car\x08r'y Case\x0b Su&its IX\x1e10\x0cIS>";
string result = Regex.Replace(str, @"[\x00-\x08\x0B\x0C\x0E-\x1F]", "");
result = result.Replace("&", "&");
result = result.Replace("'", "'");
result = result.Replace("\"", """);
result = result.Replace(">", ">");
result = result.Replace("<", "<");
Console.WriteLine(result);
Console.ReadKey();
}