【问题标题】:How to save "ą" in xml by python?如何通过python将“±”保存在xml中?
【发布时间】:2013-04-25 17:29:15
【问题描述】:

我有以下 XML:

newX.xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <country name="Liechtenstein">
    <neighbor name="Austriaą" direction="E"/>
    <neighbor name="a" direction="W"/>
</country>
</data>

Python 脚本:

# -*- coding: cp1250 -*-
import xml.etree.ElementTree as ET
xml = 'c://newX.xml'

tree = ET.parse(xml)
root = tree.getroot()
for rank in root.iter('neighbor'):
   rank.set('name', 'ą')
ET.dump(root)

我正在尝试将字符“±”设置为“名称”,但出现错误:

UnicodeDecodeError:“ascii”编解码器无法解码位置 0 中的字节 0xb9:序数不在范围内 (128)

如何解决这个问题?

【问题讨论】:

    标签: python xml unicode xml-parsing


    【解决方案1】:

    您需要使用 unicode 值。使用带有 u'' 的 unicode 文字,例如:

    rank.set('name', u'ą')
    

    这会导致:

    <data>
        <country name="Liechtenstein">
        <neighbor direction="E" name="&#216;" />
        <neighbor direction="W" name="&#216;" />
    </country>
    </data>
    

    您传递的是 cp1250 编码的字节,这些字节必须被解码为 Unicode,并且使用默认编解码器 ASCII 会自动发生这种情况。这不起作用,因为您的字节串包含十六进制值B9(cp1250 编码中的ą)的字节,这不是有效的 ASCII 值。

    您可能想了解 Python 和 Unicode:

    【讨论】:

    • 可以设置 吗? (保存在xml中)
    • @user7172:使用tree.write(outpufile, encoding='UTF-8') 写出带有“完整”字符的 XML。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多