XML非法字符的处理

在解释XML时,会因为一些非法字符解析异常,因此在解析XML前处理非法字符十分重要。 

XML的非法字符包括:

1.需去除去的非法字符范围,在W3C手册XML的非法字符可以查找到:

      \\x00-\\x08

      \\x0b-\\x0c

      \\x0e-\\x1f

2.需要替换的字符:

    字符   HTML字符字符编码
    和 &    &  &
 单引号  ’    '    '
 双引号  ”     "    "
 大于号  >     >  >
 小于号  <     &lt;  &#60

 

下面程序写个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("&", "&amp;");
            result = result.Replace("'", "&apos;");
            result = result.Replace("\"", "&quot;");
            result = result.Replace(">", "&gt;");
            result = result.Replace("<", "&lt;");
            Console.WriteLine(result);
            Console.ReadKey();
        }

    

 

转载于:https://www.cnblogs.com/wangqilong/p/10088342.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值