[英]How to get values from this 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)
您遇到問題的原因是您需要逐級解析xml。 使用findall
,我能夠在<home_goals_time>
內部獲取值。
for i in root.findall('.//home_goals_time'):
print (i.text)
None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.