当前位置:   article > 正文

python非法字符怎么处理_用Python处理xml文件中的非法字符

pycharm怎么看xml文件存在非法字符

用xml.dom.minidom.parse()解析xml文件时遇到非法字符直接报错的问题

最后的方案是把纯文本方式读入文件,然后用字符串来处理

可以得到将非法字符全部剔除的结果

[python]

#!/usr/bin/python

# -*- coding:utf-8 -*-

import string

import xml.dom.minidom

def parse_xml(file_path):

“””

Handle xml file with invalid character

[input] : path of the xml file

[output] : xml.dom.minidom.Document instance

“””

try:

xmldoc = xml.dom.minidom.parse(file_path)

except:

f = file(file_path)

s = f.read()

f.close()

ss = s.translate(None, string.printable)

s = s.translate(None, ss)

xmldoc = xml.dom.minidom.parseString(s)

return xmldoc

if __name__ == ‘__main__’:

pass

[/python]

P.S. 如果有更好的解决方案,欢迎交流

Like this:

Like Loading...

Related

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/895662
推荐阅读
相关标签
  

闽ICP备14008679号