mirror of
https://github.com/python/cpython.git
synced 2025-08-03 08:34:29 +00:00
gh-91810: Fix regression with writing an XML declaration with encoding='unicode' (GH-93426) (GH-93793)
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 d7db9dc3cc
)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
parent
86eb500068
commit
6fe7e0264f
3 changed files with 10 additions and 20 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue