Python 如何从这个XML中获取值?
我想像这样解析xml:Python 如何从这个XML中获取值?,python,xml,python-3.x,elementtree,Python,Xml,Python 3.x,Elementtree,我想像这样解析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&
<?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结构中找到问题,但没找到。我的字典总是空的。你能告诉我怎么了吗?你出现问题的原因是你需要逐级解析xml。使用
findall
,我能够获得
中的值
for i in root.findall('.//home_goals_time'):
print (i.text)
None
出现问题的原因是需要逐级解析xml。使用
findall
,我能够获得
中的值
for i in root.findall('.//home_goals_time'):
print (i.text)
None
您正在对元素调用
.attrib
,但这些元素没有属性。如果要打印元素的内部文本,请使用.text
而不是.attrib
for elem in root.iter('home_goals_time'):
print(elem.text)
您正在对元素调用
.attrib
,但这些元素没有属性。如果要打印元素的内部文本,请使用.text
而不是.attrib
for elem in root.iter('home_goals_time'):
print(elem.text)
@chepner
root.iter
递归遍历整个树@chepnerroot.iter
递归遍历整个树