Skip to content

Commit 34fae67

Browse files
Omit the XML declaration for utf-8-sig, and add tests and NEWS
Normalize the declared encoding before deciding whether to write the declaration, so that utf-8-sig is treated as utf-8: the BOM already determines the encoding. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 2916e19 commit 34fae67

3 files changed

Lines changed: 8 additions & 2 deletions

File tree

Lib/test/test_xml_etree.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,13 +933,15 @@ def test_tostring_xml_declaration_cases(self):
933933
(b"<?xml version='1.0' encoding='ISO-8859-1'?>\n"
934934
b"<body><tag>\xf8</tag></body>", 'ISO-8859-1', None),
935935
('<body><tag>ø</tag></body>', 'unicode', None),
936+
(b"\xef\xbb\xbf<body><tag>\xc3\xb8</tag></body>", 'utf-8-sig', None),
936937

937938
# ... xml_declaration = False
938939
(b"<body><tag>&#248;</tag></body>", None, False),
939940
(b"<body><tag>\xc3\xb8</tag></body>", 'UTF-8', False),
940941
(b"<body><tag>&#248;</tag></body>", 'US-ASCII', False),
941942
(b"<body><tag>\xf8</tag></body>", 'ISO-8859-1', False),
942943
("<body><tag>ø</tag></body>", 'unicode', False),
944+
(b"\xef\xbb\xbf<body><tag>\xc3\xb8</tag></body>", 'utf-8-sig', False),
943945

944946
# ... xml_declaration = True
945947
(b"<?xml version='1.0' encoding='us-ascii'?>\n"
@@ -952,6 +954,8 @@ def test_tostring_xml_declaration_cases(self):
952954
b"<body><tag>\xf8</tag></body>", 'ISO-8859-1', True),
953955
("<?xml version='1.0' encoding='utf-8'?>\n"
954956
"<body><tag>ø</tag></body>", 'unicode', True),
957+
(b"\xef\xbb\xbf<?xml version='1.0' encoding='utf-8'?>\n"
958+
b"<body><tag>\xc3\xb8</tag></body>", 'utf-8-sig', True),
955959

956960
]
957961
for expected_retval, encoding, xml_declaration in TESTCASES:

Lib/xml/etree/ElementTree.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -732,12 +732,12 @@ def write(self, file_or_filename,
732732
if not encoding:
733733
encoding = "us-ascii"
734734
with _get_writer(file_or_filename, encoding) as (write, declared_encoding):
735+
if declared_encoding.lower() == "utf-8-sig":
736+
declared_encoding = "utf-8"
735737
if method == "xml" and (xml_declaration or
736738
(xml_declaration is None and
737739
encoding.lower() != "unicode" and
738740
declared_encoding.lower() not in ("utf-8", "us-ascii"))):
739-
if declared_encoding.lower() == "utf-8-sig":
740-
declared_encoding = "utf-8"
741741
write("<?xml version='1.0' encoding='%s'?>\n" % (
742742
declared_encoding,))
743743
if method == "text":
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:meth:`xml.etree.ElementTree.ElementTree.write` now treats the ``utf-8-sig``
2+
encoding as ``utf-8`` in the XML declaration.

0 commit comments

Comments
 (0)