Python 为什么xml元素的文本类型从str到unicode有所不同?
我使用的是Python 2.7.12 当我解析以下XML文件时:Python 为什么xml元素的文本类型从str到unicode有所不同?,python,xml,python-2.7,unicode,Python,Xml,Python 2.7,Unicode,我使用的是Python 2.7.12 当我解析以下XML文件时: <?xml version="1.0" encoding="UTF-8" ?> <data>value</data> 然后将文本存储为unicode: 首先,为什么xml API表现出这种不一致性?其次,我如何强制它始终使用unicode?xml库中ElementTree.py中的XMLParser类有一个小帮助函数,如果可能,它会尝试转换为ascii,但如果无法转换,则返回unicode:
<?xml version="1.0" encoding="UTF-8" ?>
<data>value</data>
然后将文本存储为unicode:
首先,为什么xml API表现出这种不一致性?其次,我如何强制它始终使用unicode?xml库中ElementTree.py中的XMLParser类有一个小帮助函数,如果可能,它会尝试转换为ascii,但如果无法转换,则返回unicode:
def _fixtext(self, text):
# convert text string to ascii, if possible
try:
return text.encode("ascii")
except UnicodeError:
return text
这就是您将看到类型更改的原因
以下是源代码的链接:
我不知道为什么会这样,但要强制使用unicode,您可以始终使用unicodeElementTree。解析'test.xml'。getroot.text…您是否可以发布到实际源代码的链接,以便人们可以验证自己?谢谢
<?xml version="1.0" encoding="UTF-8" ?>
<data>valuè</data>
>>> type(ElementTree.parse('test.xml').getroot().text)
<type 'unicode'>
def _fixtext(self, text):
# convert text string to ascii, if possible
try:
return text.encode("ascii")
except UnicodeError:
return text