python - 如何从此 XML 中获取值?
问题描述
我想像这样解析xml:
<?xml version="1.0" ?>
<matches>
<round_1>
<match_1>
<home_team>team_5</home_team>
<away_team>team_13</away_team>
<home_goals_time>None</home_goals_time>
<away_goals_time>24;37</away_goals_time>
<home_age_average>27.4</home_age_average>
<away_age_average>28.3</away_age_average>
<score>0:2</score>
<ball_possession>46:54</ball_possession>
<shots>8:19</shots>
<shots_on_target>2:6</shots_on_target>
<shots_off_target>5:10</shots_off_target>
<blocked_shots>1:3</blocked_shots>
<corner_kicks>3:4</corner_kicks>
<fouls>10:12</fouls>
<offsides>0:0</offsides>
</match_1>
</round_1>
</matches>
我使用标准库 - xml,但我无法从内部标签中获取值。这是我的示例代码:
import xml.etree.ElementTree as et
TEAMS_STREAM = "data/stats1.xml"
tree = et.parse(TEAMS_STREAM)
root = tree.getroot()
for elem in root.iter('home_goals_time'):
print(elem.attrib)
它应该有效,但事实并非如此。我试图在 xml 结构中找到问题,但我找不到它。我总是得到空字典。你能告诉我有什么问题吗?
解决方案
您正在调用.attrib
元素,但这些元素没有属性。如果要打印元素的内部文本,请使用.text
而不是.attrib
for elem in root.iter('home_goals_time'):
print(elem.text)
推荐阅读
- python - 如何在 django 中获取上传(生成)的文件名
- ios - 公共云数据库查询不应该返回 nil
- r - R中数据框中多个选定列的乘积
- python - 如何从文件中提取项目
- swift - 使用 DateFormatter 格式化字符串日期
- python - 如何杀死屏幕上的所有敌人精灵?
- python - Ubuntu 升级到 20.0 后 Python manage.py runserver 抛出错误
- javascript - setTimeout 意外延迟内的控制台日志
- ios - 如何动态调整 UIScrollView 的大小?
- python - 为什么我会收到 +: float 和 str 不支持的错误?