0

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") 

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you @Bartosz I have tried your solution but had no such luck. I just want it to add a string "none" to the array if there is no tag name "stop_time" in the xml file but there seemed to be no change with my file output. Thank you though for your solution.
unfortunately it does not append anything to the array when I use the edited version of the code.
I added whole example to make sure you try the same.
thank you for your solution however this was the code that I am trying but it doesn't seem to be appending anything to my array like it was before.
This is much to late but I fixed it.

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.