所以这个问题基本上是第一个问题,一旦我弄清楚到底发生了什么。我阅读了很多关于编码解码和 XML 标准的文章,但我没有找到这个特定主题的答案。
import elementtree.ElementTree as ET
root = ET.Element("Prüfung")
main = ET.SubElement(root,'Test')
main.text='\xe4 '+'ä'.decode('UTF-8')
tree=ET.ElementTree(root)
tree.write('testout.xml')
我的第一个问题是在 main.text='\xe4 '+'ä'.decode('UTF-8') 行中。我明白,\xe4 是字母 ä 的代码,这是否意味着我必须将传递给我的解释器的每个字符串解码为 utf-8 才能正常工作?因为当我使用 python 的 readline 方法从 .txt 文件中读取特殊字符时,它们似乎已经被正确解码了。
一个相关但略有不同的问题是行 root = ET.Element("Prüfung")。似乎不可能在 XML 标记中使用非 ASCII 字符(至少不能使用元素树)。这是因为 XML 标准还是基本上只是另一个解码/编码问题?
请您参考如下方法:
您可以在元素名称(和元素内容)中使用非 ASCII 字符。使用 Unicode 字符串,它应该可以工作。
在 http://effbot.org/zone/element.htm#the-element-type ,它说:
All elements must have a tag, but all other properties are optional. All strings can either be Unicode strings, or 8-bit strings containing US-ASCII only.
演示程序(使用 Python 2.7 测试):
# coding: utf-8
import xml.etree.ElementTree as ET
root = ET.Element(u'Prüfung')
main = ET.SubElement(root, 'Test')
main.text = u'\xe4 ' + u'ä'
tree = ET.ElementTree(root)
tree.write('testout.xml', encoding="utf-8") # The default encoding is us-ascii
输出(在 testout.xml 中):
<Prüfung><Test>ä ä</Test></Prüfung>
上述程序在 Python 3.3+ 中也可以正常工作。前导 u 字符是多余的,但允许(u'unicode' 语法是 restored 对于 Python 3.3 中的 str 对象)。
