【问题标题】:Python ElementTree parsing unbound prefix errorPython ElementTree解析未绑定前缀错误
【发布时间】:2012-11-02 13:58:08
【问题描述】:

我正在学习 Python 中的 ElementTree。一切似乎都很好,除非我尝试使用前缀解析 xml 文件:

test.xml:

<?xml version="1.0"?>
<abc:data>
   <abc:country name="Liechtenstein" rank="1" year="2008">
   </abc:country>
   <abc:country name="Singapore" rank="4" year="2011">
   </abc:country>
   <abc:country name="Panama" rank="5" year="2011">
   </abc:country>
</abc:data>

当我尝试解析 xml 时:

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

我收到以下错误:

xml.etree.ElementTree.ParseError: unbound prefix: line 2, column 0

是否需要指定某些内容才能解析带前缀的 xml 文件?

【问题讨论】:

标签: python xml prefix elementtree


【解决方案1】:

看看这是否有效:

from bs4 import BeautifulSoup

xml_file = "test.xml"

with open(xml_file, "r", encoding="utf8") as f:
    contents = f.read()
    soup = BeautifulSoup(contents, "xml")

    items = soup.find_all("country")
    print (items)

上面将生成一个数组,然后您可以对其进行操作以实现您的目标(例如删除 html 标签等):

[<country name="Liechtenstein" rank="1" year="2008">
</country>, <country name="Singapore" rank="4" year="2011">
</country>, <country name="Panama" rank="5" year="2011">
</country>]

【讨论】:

    【解决方案2】:

    将 abc 命名空间添加到您的 xml 文件中。

    <?xml version="1.0"?>
    <abc:data xmlns:abc="your namespace">
    

    【讨论】:

    • 但是如果不是我的 XML 需要改变,我只需要解析它呢?
    • 我支持@Mark Allen 的问题/评论!我有同样的问题。当然,可以根据具体情况编辑该文件,但我有许多大(且不统一)的 xml 文件。当然有办法解决这个问题
    猜你喜欢
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多