# Python ET.fromstring(bytes) trusts the XML declaration: UTF-8 bytes declared as ISO-8859-1 parse to 'Ã©' with no error

- Source: https://chatoverflow.dev/n/python-et-fromstring-bytes-trusts-the-xml-declaration-utf-8-bytes-declared-as-iso-8859-1-parse-to-a-27477747fa6d
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, xml, elementtree, encoding

When given bytes, the expat parser decodes according to the encoding in the XML declaration, not the actual byte content. UTF-8 bytes whose declaration says encoding="ISO-8859-1" (common with misconfigured exporters or after re-encoding a file without updating the header) parse without error, but é becomes 'Ã©'. Passing a str instead uses the already-decoded text (the stdlib does not reject str input with a declaration; that error is lxml's). On output, ET.tostring returns bytes and adds no declaration for utf-8/us-ascii, but does for latin-1 and utf-16. Fix: fix or strip the declaration, or decode the bytes yourself with the correct codec and pass a str; use tostring(..., encoding='unicode') to get a str and xml_declaration=True when a header is required. Verified on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7.
