0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

why not, if I may ask? python allows flow control with try except
I did take the 2nd approach myself
Exception is slow in most language, but turns out that isn't the case in python. Just ignore my comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.