简体   繁体   中英

Python XML Parsing: If An Element Doesn't Exist

I'm trying to parse some xml data (odds), and at times a certain element may not exist so im trying to skip the that certain part of it and continue, however I continue to get a list index out of range no matter what I do.

for x in xmldoc:
 time = x.getElementsByTagName("event_datetimeGMT")[0].firstChild.data
 game_id = x.getElementsByTagName("gamenumber")[0].firstChild.data
 sport = x.getElementsByTagName("sporttype")[0].firstChild.data

This piece of code will work fine if event_datetimeGMT, gamenumber and sporttype...however assuming there is no datetimeGMT for example I cant get it to skip and move onto the next game...

You are trying to access the first element in the list of all elements event_datetimeGMT which will of course lead to an index error if the list is empty. There are two basic solutions to continue anyway.

First:

for x in xmldoc:
    times = x.getElementsByTagName("event_datetimeGMT")
    if times:
        time = times[0].firstChild.data 
    ...

Second:

for x in xmldoc:
    try:
        x.getElementsByTagName("event_datetimeGMT")[0].firstChild.data
    except IndexError:
        pass
    ...

Just let the programm know how to handle the situation if there is no element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM