R.J. Jackson
R.J. Jackson

Reputation: 125

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...

Upvotes: 0

Views: 1370

Answers (1)

Lawrence Benson
Lawrence Benson

Reputation: 1406

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.

Upvotes: 2

Related Questions