过滤XML中的非法字符

在用Dom4J处理XML文件时,抛出了这个异常:

An invalid XML character (Unicode: 0x8) was found in the CDATA section.

通过Google的缓存里面找到了一个解决办法,原文链接(http://zongfeng.bloghome.cn/posts/77742.html )现在访问不了。文章里说,

一般xml中如果含有&等字符,可以通过CDATA来过滤,但是含有一些不认识的特殊字符时候就会不起作用,下面是从别人那儿拿来的一个过滤方法,过滤xml中的非法字符:
//XML标准规定的无效字节为:

/*
0×00 – 0×08
0x0b – 0x0c
0x0e – 0x1f
*/

//所以很简单,输出的时候过滤这些字符就万无一失了,下面是PHP的实现。

/* PHP 实现 */
function XmlSafeStr($s)
{
return preg_replace(“/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/”,”,$s);
}

W3C的XML规范中关于字符的定义请参看这里:http://www.w3.org/TR/2004/REC-xml-20040204/#charsets
过滤非法字符对应的Java版本如下:

    public String filter(String s)
    {
        return s.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
    }
Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks
  • FriendFeed
  • Google Buzz
  • PDF
  • RSS

2 comments to 过滤XML中的非法字符

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">