• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python xml解析中文乱码怎么办

python 搞java代码 3年前 (2022-05-21) 37次浏览 已收录 0个评论

python解析xml文件,出现异常信息如下:

<a href="https://www.gaodaima.com/tag/xml" title="查看更多关于xml的文章" target="_blank">xml</a>.parsers.expat.ExpatError: not well-formed (invalid token): line 13, column 31

www#gaodaima.com来源gao.dai.ma.com搞@代*码网搞代码

相关推荐:《Python入门教程》

解决方式:

将文件重新编码成utf-8格式就可以了。

在linux下一种取巧的解决方式:

对于中文,这里选了一种取巧的方法。即先通过iconv命令将xml文件变成utf-8格式,然后将xml中指定编码格式的内容去掉即可。

可参考如下代码:

cmd = "iconv " + filename + " -t "utf-8" >utf.tmp"
os.system(cmd)
utf_filename = "utf.tmp"
f = open(utf_filename)
data = f.read()
f.close()
os.system("rm -f utf.tmp")
#----delete the encode type in  xml file-----
#result = re.sub(regex, newstring, subject)
data = data.replace('encoding="GB2312"', '')
data = data.replace('encoding="gb2312"', '')
#self.dom.unlink
self.dom = xml.dom.minidom.parseString( data )

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python xml解析中文乱码怎么办

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址