如何在 Python 3.5 中将显式 unicode 写入 XML 文件?

How to write explicit unicode to XML file in Python 3.5?

我只想创建一个 XML 文件来执行如下操作:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    jos&#233;
</Response>

我正在尝试这样写 josé。

str("josé".encode())

但是我在文件中写了这个:

b'jos\xc3\xa9'

如果您已经有一个作为 Unicode 字符串的 XML 文档,然后将其写入一个文件,这样您就会看到 jos&#233; 而不是 josé,您可以使用 xmlcharrefreplace 错误处理程序:

with open('response.xml', 'w', encoding='ascii', errors='xmlcharrefreplace') as file:
    file.write(xml_text)

如果您使用库构建 XML 文档(推荐),则使用适当的 API 将对象保存到文件中,例如:

#!/usr/bin/env python3
from xml.etree import ElementTree as ET

root = ET.Element('Response')
root.text = 'josé'
with open('response.xml', 'wb') as file:
    ET.ElementTree(root).write(file, xml_declaration=True)

response.xml:

<?xml version='1.0' encoding='us-ascii'?>
<Response>jos&#233;</Response>

参见 ElementTree.write()