2017-03-16 38 views
0

我在Python 2.7.12。爲什麼xml元素的文本類型從str到unicode有所不同?

當我解析下面的XML文件:

<?xml version="1.0" encoding="UTF-8" ?> 
<data>value</data> 

,我通過檢查元素的文本類型:

>>> from xml.etree import ElementTree 
>>> type(ElementTree.parse('test.xml').getroot().text) 
<type 'str'> 

我很驚訝地看到它是一個str - 我的預期是一個unicode。只有當我介紹了非ASCII字符的XML文件,例如:

<?xml version="1.0" encoding="UTF-8" ?> 
<data>valuè</data> 

則文本存儲爲unicode

>>> type(ElementTree.parse('test.xml').getroot().text) 
<type 'unicode'> 

首先,爲什麼用xml API出這種有點不一致,其次我該如何強制它始終使用unicode

+0

我不能說爲什麼它是這樣,但給力的unicode,你可以隨時'的Unicode(ElementTree.parse(「的test.xml」) .getroot()。text)'... – zvone

回答

1

在ElementTree.py的XMLParser的類(從XML庫)有嘗試轉換爲ASCII如果可能的話小助手功能,但返回unicode的,如果它不能做到這一點:

def _fixtext(self, text): 
    # convert text string to ascii, if possible 
    try: 
     return text.encode("ascii") 
    except UnicodeError: 
     return text 

這就是爲什麼你會看到類型的變化。

這裏是源代碼的鏈接: https://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py#l1519

+0

你可以發佈鏈接到實際的源代碼,以便人們可以驗證自己嗎?謝謝 – har07

相關問題