python-xml : Not well-formed (invalid token) - xml. etree utf模式

标签 python elementtree parsexml

我有以下 XML 文件结构:

<doc id="4611827073121129112">
<class name="tag:September_11" val="-0.079590" />
<class name="tag:Theater" val="-0.134223" />
<class name="tag:Adaptation" val="-0.106678" />
<class name="tag:Paranormal" val="-0.183504" />
<class name="tag:Magic" val="-0.179214" />
<class name="tag:Comedy_Drama" val="-0.044658" />
<class name="tag:Fashion" val="-0.280695" />
<class name="tag:Running" val="0.160316" />
<class name="tag:Construction" val="-0.072044" />
<class name="tag:Suspense_Thriller" val="-0.370302" />
<class name="tag:Space" val="-0.239723" />
<class name="tag:Police" val="-0.139019" />
<class name="tag:Hip-Hop_&_Rap_Music" val="-0.290353" />
<class name="tag:Surfing" val="-0.027105" />
<class name="tag:Halloween" val="-0.236606" />
<class name="tag:Mystery_&_Suspense" val="0.005384" />
<class name="tag:Educational" val="-0.166370" />
<class name="tag:Biography" val="-0.126149" />
<class name="tag:Religion" val="-0.034275" />
<class name="tag:Cartoon" val="-0.487169" />
<class name="tag:Auto_Racing" val="-0.047648" />
<class name="tag:Pets" val="-0.118809" />
</doc>

文件没有 xml 扩展名,例如文件名是 test.values

首先尝试我决定使用 python shell:我使用的是 Anaconda 版本的 python:

Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('test.values')

出现以下错误:

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

仔细查看该行后:

<class name="tag:Hip-Hop_&_Rap_Music" val="-0.290353" />

我意识到它有 & 并且我猜测 xml.etree 包不会以 utf 模式打开文件:

我手动删除了 &,一切正常。但问题是我必须读取大量文件并进行解析。根据我的谷歌搜索,我找不到任何以 utf-8 模式显示 etree 包打开文件的示例。我该如何解决这个问题?

最佳答案

你是对的,它是 &,但它与 Unicode 无关(尽管在你解决这个问题后可能会出现 Unicode 问题。

您不能在 XML 的属性值中使用 & 号或小于号,除非您将其转义(分别为 & 或 <)。因此,无论编写 XML 的程序是什么,都应该修复以检测和重新编码这些字符。

关于python-xml : Not well-formed (invalid token) - xml. etree utf模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28821057/

相关文章:

python 2.7.5 请求和证书验证失败

python - 在属性 ID 相同的地方合并 XML 文件 Python

python - 使用 namespace 解析 XML

javascript - `$xml = $( xmlDoc )` 是做什么的?

jquery - 从 ScriptSharp 读取 XML 字符串

python - Python 中的轻量级对象-> 数据库

python - 无法再在 Ubuntu 12.04 LTS(Precise Pangolin)中使用 pip 安装任何 Python 2 包

python - 在 Modbus Python 中读写浮点型

python - 给定元素的 xml.etree.ElementTree.write() 整数值可以吗?

python - 在 Mac 上解析 XML 时出现 UnicodeDecodeError,但在 PC 上可以正常工作