ElementTree不以UTF-8编写数据

时间:2014-11-28 15:56:34

标签: python xml utf-8 elementtree

我从数据库中提取数据并尝试从此数据创建XML文件。数据采用UTF-8格式,可以包含ášč等字符。这是代码:

import xml.etree.cElementTree as ET

tree = ET.parse(metadata_file)
# ..some commands that alter the XML..
tree.write(metadata_file, encoding="UTF-8")

编写数据时,脚本失败并显示:

Traceback (most recent call last):
  File "get-data.py", line 306, in <module>
    main()
  File "get-data.py", line 303, in main
    tree.write(metadata_file, encoding="UTF-8")
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 820, in write
    serialize(write, self._root, encoding, qnames, namespaces)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
    _serialize_xml(write, e, encoding, qnames, None)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
    _serialize_xml(write, e, encoding, qnames, None)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 937, in _serialize_xml
    write(_escape_cdata(text, encoding))
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1073, in _escape_cdata
    return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 32: ordinal not in range(128)

防止这种情况的唯一方法是使用以下方法解码写入XML文件的数据:

text = text.decode('utf-8')

但是结果文件将包含例如&#269;而不是č。知道如何将数据写入文件并保存在UTF-8中吗?

修改

这是脚本的作用示例:

]$ echo "<data></data>" > test.xml
]$ cat test.xml
<data></data>
]$ python
Python 2.7.5 (default, Nov  3 2014, 14:33:39)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.cElementTree as ET
>>> tree = ET.parse('./test.xml')
>>> root = tree.getroot()
>>> new = ET.Element("elem")
>>> new.text = "á, š, or č"
>>> root.append(new)
>>> tree.write('./text.xml', encoding="UTF-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 820, in write
    serialize(write, self._root, encoding, qnames, namespaces)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
    _serialize_xml(write, e, encoding, qnames, None)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 937, in _serialize_xml
    write(_escape_cdata(text, encoding))
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1073, in _escape_cdata
    return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

2 个答案:

答案 0 :(得分:1)

啊,终于明白了,这是正确的方法:

]$ echo "<data></data>" > text.xml
]$ python
Python 2.7.5 (default, Nov  3 2014, 14:26:24)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.cElementTree as ET
>>>
>>> tree = ET.parse('./test.xml')
>>> root = tree.getroot()
>>> new = ET.Element("elem")
>>> new.text = "á, š, or č".decode('utf-8')
>>> root.append(new)
>>> tree.write('./textout.xml', encoding="UTF-8")
>>>
>>> exit()
]$ cat textout.xml
<?xml version='1.0' encoding='UTF-8'?>
<data><elem>á, š, or č</elem></data>

在我的原始解决方案中,我在write()中将其编码为UTF-8,但未使用.decode('utf-8')对其进行解码。

答案 1 :(得分:0)

这个问题并不能说明metadata_file是什么类型的对象。

如果使用普通文件对象,则没有错误,输出符合预期:

>>> import xml.etree.cElementTree as ET
>>> stream = open('test.xml', 'wb+')
>>> stream.write(u"""\
... <root>characters such as á, š, or č.</root>
... """.encode('utf-8'))
>>> stream.seek(0)
>>> tree = ET.parse(stream)
>>> stream.close()
>>> ET.tostring(tree.getroot())
'<root>characters such as &#225;, &#353;, or &#269;.</root>'
>>> stream = open('test.xml', 'w')
>>> tree.write(stream, encoding='utf-8', xml_declaration=True)
>>> stream.close()
>>> open('test.xml').read()
"<?xml version='1.0' encoding='utf-8'?>\n<root>characters such as \xc3\xa1, \xc5\xa1, or \xc4\x8d.</root>"