如何使用ElementTree正确解析utf-8 xml?
问题描述:
我需要帮助,以了解为什么解析我的xml文件*与xml.etree.ElementTree会产生以下错误。如何使用ElementTree正确解析utf-8 xml?
* 我的测试xml文件包含阿拉伯字符。
任务: 打开并解析utf8_file.xml
文件。
我第一次尝试:
import xml.etree.ElementTree as etree
with codecs.open('utf8_file.xml', 'r', encoding='utf-8') as utf8_file:
xml_tree = etree.parse(utf8_file)
结果1:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 236-238: ordinal not in range(128)
我的第二次尝试:
import xml.etree.ElementTree as etree
with codecs.open('utf8_file.xml', 'r', encoding='utf-8') as utf8_file:
xml_string = etree.tostring(utf8_file, encoding='utf-8', method='xml')
xml_tree = etree.fromstring(xml_string)
结果2:
AttributeError: 'file' object has no attribute 'getiterator'
请解释一下上面的错误,并在可能的解决方案发表意见。
答
将解码字节留给解析器;做不解码第一:
import xml.etree.ElementTree as etree
with open('utf8_file.xml', 'r') as xml_file:
xml_tree = etree.parse(xml_file)
的XML文件必须包含在第一线处理解析器解码的足够信息。如果标题丢失,解析器必须假定使用了UTF-8。
因为它是保存此信息的XML标头,所以解析器有责任进行所有解码。
您的第一次尝试失败,因为Python试图再次编码 Unicode值,以便解析器可以按预期处理字节字符串。第二次尝试失败,因为etree.tostring()
需要解析树作为第一个参数,而不是unicode字符串。
优秀,它似乎比我想象的更容易。即使“没有BOM”的“utf-8”文件也能正确解析。 – minerals
没有BOM的UTF-8是标准; *带* BOM主要是微软希望能够更容易地自动检测UTF-8以外的8位编码。 –
'etree.parse(a_file)'默认处理Unicode。然而'etree.fromstring(a_string)'直到Python 3.x(请参阅http://bugs.python.org/issue11033)才能解析字符串,所以必须手动对其进行编码,如'etree.fromstring( a_string.encode( 'UTF-8'))'。 –