首页 > 解决方案 > 如何从此 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 结构中找到问题,但我找不到它。我总是得到空字典。你能告诉我有什么问题吗?

标签: pythonxmlpython-3.xelementtree

解决方案


您正在调用.attrib元素,但这些元素没有属性。如果要打印元素的内部文本,请使用.text而不是.attrib

for elem in root.iter('home_goals_time'):
    print(elem.text)

推荐阅读