Reputation: 2559
I am very new to python however I have managed to create a parser python program which calls a web-based xml file and stores elements within an array. These arrays containing the xml elements are then read and sent to a localhost database.
I am having an "IndexError" issue when writing to my database as one of the arrays contains less elements than the others which means this error is produced. Does anyone have any suggestions as to how to allow me to append a string to the array instead - if there is no element present in the xml file?
The code which gets the xml element and assigns it to the "stop_times" array -
stop_times = []
for stop in event_main:
stop_time = stop.getElementsByTagName("stop_time")[0]
stop_times.append(stop_time)
Is it possible to check if the "stop_time" variable is null/empty and if so, stop_time is equal to string "null"? Any help is much appreciated, Karen
EDIT: MY CORRECT CODE (which may help others):
stop_times = []
for stop in event_main:
try:
stop_time = stop.getElementsByTagName("stop_time")[0].childNodes[0].nodeValue
stop_times.append(stop_time)
except IndexError:
stop_times.append("none")
Upvotes: 0
Views: 151
Reputation: 1860
If I understand you correct, this might help you.
stop_times = []
for stop in event_main:
try:
stop_time = stop.getElementsByTagName("stop_time")[0]
stop_times.append(stop_time.firstChild.nodeValue)
except IndexError:
stop_times.append("none")
break
Upvotes: 1