如何用python2.7elementtree模块和unicode呈现xml

2024-10-03 23:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码在unicode输入上抛出了一个致命的异常。我正在使用ElementTree构建一个xml文档,并使用tostring()打印它。我尝试过传入unicode对象,并将它们编码为UTF-8 bytestring,但没有任何区别。我不知道我是做错了什么还是模块中有bug。你知道吗

这是一个小样本来复制它。你知道吗

#!/usr/bin/python

from __future__ import unicode_literals, print_function
from xml.etree.ElementTree import Element, SubElement, tostring
import xml.etree.ElementTree as ET
import time

def main():
    xml = Element('build_summary')
    mpversion = SubElement(xml, 'magpy_version')
    mpversion.text = '1.2.3.4'
    version = SubElement(xml, 'version')
    version.text = '11.22.33.44'
    date = SubElement(xml, 'date')
    date.text = time.strftime("%a %b %-d %Y", time.localtime())
    args = SubElement(xml, 'args')
    args.text = 'build args'
    issues = SubElement(xml, 'issues')
    # Add the repos and the changes in them
    changelog = 'this is the changelog \u2615'
    #changelog = 'this is the changelog'
    print("adding changelog:", changelog)
    repository = SubElement(issues, 'repo')
    reponame = SubElement(repository, 'reponame')
    reponame.text = 'repo name'
    repoissues = SubElement(repository, 'repoissues')
    #repoissues.text = changelog.encode('UTF-8', 'replace')
    repoissues.text = changelog

    # Generate a string, reparse it, and pretty-print it.
    #ET.dump(xml)
    #xml.write('myoutput.xml')
    rough = tostring(xml, encoding='UTF-8', method='xml')
    #rough = tostring(xml)
    print(rough)

if __name__ == '__main__':
    main()

这将产生以下结果:

msoulier@anton:~$ python treetest.py
adding changelog: this is the changelog ☕
Traceback (most recent call last):
File "treetest.py", line 38, in <module>
    main()
File "treetest.py", line 33, in main
    rough = tostring(xml, encoding='UTF-8', method='xml')
File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1127, in tostring
    return "".join(data)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 22: ordinal not in range(128)

那么,我做错什么了?奇怪的是,元素树.dump工作正常,但文件说,不要使用它的任何错误调试。你知道吗


Tags: thetextinimportmainversionargschangelog