summaryrefslogtreecommitdiffstats
path: root/Lib/xml
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2022-06-16 16:16:42 (GMT)
committerGitHub <noreply@github.com>2022-06-16 16:16:42 (GMT)
commita27f3ccea5d83917ef5d9d4c6b43d65e96c06ed3 (patch)
tree53dd05865310333ba521f3d284d55109b4da4e86 /Lib/xml
parent5c10c365fef3ca480c930cb379bf1d0ebadcd911 (diff)
downloadcpython-a27f3ccea5d83917ef5d9d4c6b43d65e96c06ed3.zip
cpython-a27f3ccea5d83917ef5d9d4c6b43d65e96c06ed3.tar.gz
cpython-a27f3ccea5d83917ef5d9d4c6b43d65e96c06ed3.tar.bz2
gh-91810: Fix regression with writing an XML declaration with encoding='unicode' (GH-93426) (GH-93790)
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. (cherry picked from commit d7db9dc3cc5b44d0b4ce000571fecf58089a01ec) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
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 58da7c8..2503d9e 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