summaryrefslogtreecommitdiffstats
path: root/Lib/xml
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2022-06-14 04:25:33 (GMT)
committerGitHub <noreply@github.com>2022-06-14 04:25:33 (GMT)
commitd7db9dc3cc5b44d0b4ce000571fecf58089a01ec (patch)
treecc636ef403b128d3d7786e3885a9aa68e7e6ca15 /Lib/xml
parent8352e322e87ba39c71e578b65ad8ae156ca3e0c7 (diff)
downloadcpython-d7db9dc3cc5b44d0b4ce000571fecf58089a01ec.zip
cpython-d7db9dc3cc5b44d0b4ce000571fecf58089a01ec.tar.gz
cpython-d7db9dc3cc5b44d0b4ce000571fecf58089a01ec.tar.bz2
gh-91810: Fix regression with writing an XML declaration with encoding='unicode' (GH-93426)
Suppress writing an XML declaration in open files in ElementTree.write() with encoding='unicode' and xml_declaration=None. If file patch is passed to ElementTree.write() with encoding='unicode', always open a new file in UTF-8.
Diffstat (limited to 'Lib/xml')
-rw-r--r--Lib/xml/etree/ElementTree.py12
1 files changed, 5 insertions, 7 deletions
diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py
index a5cc65e..1dc8035 100644
--- a/Lib/xml/etree/ElementTree.py
+++ b/Lib/xml/etree/ElementTree.py
@@ -731,6 +731,7 @@ class ElementTree:
with _get_writer(file_or_filename, encoding) as (write, declared_encoding):
if method == "xml" and (xml_declaration or
(xml_declaration is None and
+ encoding.lower() != "unicode" and
declared_encoding.lower() not in ("utf-8", "us-ascii"))):
write("<?xml version='1.0' encoding='%s'?>\n" % (
declared_encoding,))
@@ -757,13 +758,10 @@ def _get_writer(file_or_filename, encoding):
except AttributeError:
# file_or_filename is a file name
if encoding.lower() == "unicode":
- file = open(file_or_filename, "w",
- errors="xmlcharrefreplace")
- else:
- file = open(file_or_filename, "w", encoding=encoding,
- errors="xmlcharrefreplace")
- with file:
- yield file.write, file.encoding
+ encoding="utf-8"
+ with open(file_or_filename, "w", encoding=encoding,
+ errors="xmlcharrefreplace") as file:
+ yield file.write, encoding
else:
# file_or_filename is a file-like object
# encoding determines if it is a text or binary writer