python 过滤xml非法字符 :not well-formed (invalid token)错误处理

python处理xml报错:

xml.etree.ElementTree.ParseError: not well-formed (invalid token):

查询得知xml有不支持的字符范围

出现这个错误的原因是,xml文件中含有非法字符,是一个bad xml,即不符合xml规范的.

由于xml文件是第三方提供,只能自己这里处理掉xml中的非法字符

python过滤方法:

    text=open("badxml.xml").read()
    text=re.sub(u"[\x00-\x08\x0b-\x0c\x0e-\x1f]+",u"",text)
    root=ElementTree.fromstring(text)

替换掉非法字符即可

适用于不会使用到非法字符的情况

posted @ 2013-08-13 19:46  zsc347  阅读(16915)  评论(0)    收藏  举报