我在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文件答案 0 :(得分:13)
将abc名称空间添加到xml文件中。
<?xml version="1.0"?>
<abc:data xmlns:abc="your namespace">
答案 1 :(得分:0)
看看是否可行:
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>]