我的xml文件中有一个这样的结构:
<questions>
<q question="Where were Jim and his mother going?" answer="The school"/>
<q question="What color was the ball?" answer="orange"/>
我正在尝试用python中的minidom解析它
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
,我得到这个错误:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 524, in __getitem__
KeyError: 'answer'
我在这里错过了什么?
从你发布的代码中我可以看出,绝对没有任何问题。
但是,考虑到您提供的XML只是一个摘录,并且没有显示</questions>
结束标记,我怀疑可能在某个地方有一个缺少answer
属性的q
元素。