【问题标题】:elementTree cannot parse unicode xmlelementTree 无法解析 unicode xml
【发布时间】:2012-04-25 22:46:27
【问题描述】:

我有以下 xml:

<Earth>
 <country name="Česká republika" population="8900000">
    <capital>Praha1</capital>        
  </country>
</Earth>

但是当我尝试解析它失败并出现错误:

 xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 2, column 20

我的代码:

 tree=etree.parse(input) # input -> file.xml

【问题讨论】:

  • XML文件的编码是什么?您需要确保解码为 Unicode。
  • 非常类似于stackoverflow.com/questions/147741/…尝试用正确的编码打开
  • 是的,但我没有以任何方式打开它,我只是使用文件名作为 ET.parse 的参数,这就是我无法手动设置编码的原因(或者我是不知道ET方法,可以这样做)

标签: python xml xml-parsing elementtree


【解决方案1】:

正如 arhimmel 指出的那样,这个问题很可能是编码问题。 etree.parse 允许传递类似文件的对象以及路径,因此您可以尝试在代码顶部添加import codecs,然后将input 替换为codecs.open("file.xml", encoding="UTF-8")

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2021-02-06
    相关资源
    最近更新 更多