Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么xml元素的文本类型从str到unicode有所不同?_Python_Xml_Python 2.7_Unicode - Fatal编程技术网

Python 为什么xml元素的文本类型从str到unicode有所不同?

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:

我使用的是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:

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