【发布时间】:2022-01-31 10:43:20
【问题描述】:
为了为 ASP.NET 生成资源 XML 文件,第三方工具需要 BOM(迁移到工具的新版本时)。同时需要<?xml version='1.0' encoding='utf-8'?>这样的XML prolog。
问题是在使用ElementTree命令时...
tree.write(lang_resx_fpath, encoding='utf-8')
生成的文件不包含 BOM。使用命令时...
tree.write(lang_resx_fpath, encoding='utf-8-sig')
结果确实包含 BOM;但是,XML 序言包含 encoding='utf-8-sig'。
我应该如何生成包含 BOM 和 encoding='utf-8' 的文件?
更新:
我已经通过再次读取、替换和写入文件来解决它,就像这样......
with open(lang_resx_fpath, 'r', encoding='utf-8-sig') as f:
content = f.read()
content = content.replace("encoding='utf-8-sig'", "encoding='utf-8'")
with open(lang_resx_fpath, 'w', encoding='utf-8-sig') as f:
f.write(content)
无论如何,有没有更清洁的解决方案?
更新:我已经创建了https://bugs.python.org/issue46598,并且我还编写了修复程序 (https://github.com/python/cpython/pull/31043)。
【问题讨论】:
-
正在禁用带有
xml_declaration=False的 xml prolog 作为 .write() 参数选项? -
@MaciejWrobel:不。XML prolog 必须存在。
标签: python xml utf-8 elementtree byte-order-mark