解析xml文件出错:
使用
xml.etree.ElementTree.parse
读xml文件报错:ValueError: multi-byte encodings are not supported
原代码
import xml.etree.ElementTree as ET
# specify the path to your XML file
xml_path = "./402_fd2.xml"
# parse the XML file using ElementTree
tree = ET.parse(xml_path) #报错
原因分析:
需要解析的xml文件中的表头是
<?xml version='1.0' encoding='big5'?>
,其编码方式为‘big5’,而xml.etree.ElementTree.parse
支持的是’utf-8‘编码方式。
解决方案:
读文件缓存在buffer中转换为utf-8编码格式,再根据自身需求选择解析字符串还是解析xml的方式。
import xml.etree.ElementTree as ET
import xml.dom.minidom
# specify the path to your XML file
xml_path = "./402_fd2.xml"
# parse the XML file using ElementTree
with open(xml_path, 'r', encoding='utf-8') as f:
datasource = f.read()
f.close()
ET.fromstring(datasource) # 将xml转换字符串
DOMTree = xml.dom.minidom.parseString(datasource)
# 这里有两个解决办法:
# 1.将字符串转换为xml解析
# 2.直接解析字符串
心得:
1.不推荐直接使用记事本修改编码方式,会导致读不出xml;
2.xml文件用浏览器打开时出现的坑:
(1)不要修改原有的编码格式
(2)<?xml-stylesheet type='text/xsl' href='<local file path>\signal.xsl'?>
这个是引用的文件,检查自己是否有这个文件,并在本地中保存该文件