2013-07-31 54 views
0

請看下面的代碼創建循環:從XML數據

from xml.dom import minidom 
xmldoc = minidom.parse("C:\Users\...\xml") #This is just the address to the document 
soccerfeed = xmldoc.getElementsByTagName("SoccerFeed")[0] 
soccerdocument = soccerfeed.getElementsByTagName("SoccerDocument")[0] 
competition = soccerdocument.getElementsByTagName("Competition")[0] 
country = competition.getElementsByTagName("Country")[0].firstChild.data 
name = competition.getElementsByTagName("Name")[0].firstChild.data 
season = competition.getElementsByTagName("Stat")[1].firstChild.data 
matchday = competition.getElementsByTagName('Stat')[3].firstChild.data 
lst = [country, name, season, "matchday: "+ matchday]  
print lst 

#Match Data 
MatchData = soccerdocument.getElementsByTagName("MatchData")[0]  
for MatchInfo in MatchData: 
    MatchInfo = MatchData.getElementsByTagName("MatchInfo")[0] 
    Attendance = MatchInfo.getElementsByTagName("Attendance")[0].firstChild.data  
    Result = MatchInfo.getElementsByTagName("Result")[0] 
    print (MatchInfo, "Attendance: "+ Attendance) 

所以我剛纔寫的代碼從XML文件解析的一些數據。我不斷收到以下錯誤:

Traceback (most recent call last): 
    File "C:\Users\Javi\Desktop\csvfile.py", line 28, in <module> 
    for MatchInfo in MatchData: 
TypeError: iteration over non-sequence 

如何解決此問題?

+0

哪些呢打印MatchData輸出? – tobspr

+0

你考慮過ElementTree還是更好:lxml? 這比使用minidom更快更容易。 –

回答

0

循環返回值getElementsByTagName

替換以下行

MatchData = soccerdocument.getElementsByTagName("MatchData")[0] 

MatchData = soccerdocument.getElementsByTagName("MatchData")