赞
踩
用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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。