Question

I have a structure like this in my xml file:

<questions>
    <q question="Where were Jim and his mother going?" answer="The school"/>
    <q question="What color was the ball?" answer="orange"/>

I am trying to parse it with minidom in python

questionsblock = s.getElementsByTagName('questions')    
questions = questionsblock[0].getElementsByTagName('q')
counter = 1
for q in questions:
    question = q.attributes['question'].value
    answer = q.attributes['answer'].value

and I am getting this error:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 524, in __getitem__
KeyError: 'answer'

what am I missing here?

Was it helpful?

Solution

As far as I can tell from the code you posted, there is absolutely nothing wrong.

However, considering that the XML you provided in only an extract, and does not show the </questions> closing tag, I suspect there may be a q element somewhere with a missing answer attribute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top