How to correctly parse utf-8 xml with ElementTree? How to correctly parse utf-8 xml with ElementTree? xml xml

How to correctly parse utf-8 xml with ElementTree?


Leave decoding the bytes to the parser; do not decode first:

import xml.etree.ElementTree as etreewith open('utf8_file.xml', 'r') as xml_file:    xml_tree = etree.parse(xml_file)

An XML file must contain enough information in the first line to handle decoding by the parser. If the header is missing, the parser must assume UTF-8 is used.

Because it is the XML header that holds this information, it is the responsibility of the parser to do all decoding.

Your first attempt failed because Python was trying to encode the Unicode values again so that the parser could handle byte strings as it expected. The second attempt failed because etree.tostring() expects a parsed tree as first argument, not a unicode string.