diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py index 0c944516ae115f1..2af2d1fd64520b1 100644 --- a/Lib/test/test_xml_etree.py +++ b/Lib/test/test_xml_etree.py @@ -933,6 +933,7 @@ def test_tostring_xml_declaration_cases(self): (b"\n" b"\xf8", 'ISO-8859-1', None), ('ø', 'unicode', None), + (b"\xef\xbb\xbf\xc3\xb8", 'utf-8-sig', None), # ... xml_declaration = False (b"ø", None, False), @@ -940,6 +941,7 @@ def test_tostring_xml_declaration_cases(self): (b"ø", 'US-ASCII', False), (b"\xf8", 'ISO-8859-1', False), ("ø", 'unicode', False), + (b"\xef\xbb\xbf\xc3\xb8", 'utf-8-sig', False), # ... xml_declaration = True (b"\n" @@ -952,6 +954,8 @@ def test_tostring_xml_declaration_cases(self): b"\xf8", 'ISO-8859-1', True), ("\n" "ø", 'unicode', True), + (b"\xef\xbb\xbf\n" + b"\xc3\xb8", 'utf-8-sig', True), ] for expected_retval, encoding, xml_declaration in TESTCASES: diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py index 7708d38b7759cb1..951540eb9f45e90 100644 --- a/Lib/xml/etree/ElementTree.py +++ b/Lib/xml/etree/ElementTree.py @@ -732,6 +732,8 @@ def write(self, file_or_filename, if not encoding: encoding = "us-ascii" with _get_writer(file_or_filename, encoding) as (write, declared_encoding): + if declared_encoding.lower() == "utf-8-sig": + declared_encoding = "utf-8" if method == "xml" and (xml_declaration or (xml_declaration is None and encoding.lower() != "unicode" and diff --git a/Misc/NEWS.d/next/Library/2026-08-12-22-15-00.gh-issue-90756.Qn7dLm.rst b/Misc/NEWS.d/next/Library/2026-08-12-22-15-00.gh-issue-90756.Qn7dLm.rst new file mode 100644 index 000000000000000..dc15291d54a4ea4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-12-22-15-00.gh-issue-90756.Qn7dLm.rst @@ -0,0 +1,2 @@ +:meth:`xml.etree.ElementTree.ElementTree.write` now treats the ``utf-8-sig`` +encoding as ``utf-8`` in the XML declaration.