Python xml.dom.minidom 统一码

标签 python unicode

我试图在 python 中创建一个 xml 文档,但是我正在使用的一些字符串是用 unicode 编码的。有没有办法使用 xml.dom.minidom 使用 unicode 字符串创建文本节点?我可以使用其他模块吗?

谢谢。

最佳答案

理论上,根据 the docs :

the DOMString defined in the recommendation is mapped to a Python string or Unicode string. Applications should be able to handle Unicode whenever a string is returned from the DOM.

所以您应该可以使用 Unicode 字符串或 Python 字符串(utf-8 是 XML 中的默认编码)。

实际上,在 Python 2 中,我有时会遇到 xml.dom 中的 Unicode 字符串问题(我几乎完全从它切换到 ElementTree,所以我不确定最近的 Python 2 版本中仍然存在问题。

如果您确实在直接使用 Unicode 字符串时遇到问题,我想您会想尝试使用编码字符串,例如,thedoc.createTextNode(u'pié'.encode('utf-8')).

当然,在 Python 3 中,str 是 Unicode,因此在这方面一切都大不相同;-)。

关于Python xml.dom.minidom 统一码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1610948/

相关文章:

python,正则表达式拆分和特殊字符

python - 如何从命令行导出数据(Python 程序的结果)?

python 请求

Python 无法解码 JSON 对象

python - Pygame如何改变背景颜色而不删除其他任何东西

python - 仅匹配 Python re 中的 unicode 字母

python - Scrapy 无法从 URL 下载图像

python-2.7 - 获取适当长度的表情符号

python - 如何使用 Python 3 访问二进制和文本数据以进行电子邮件处理?

database - 对 postgres 中的所有列类型使用 unicode(255)?