我的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'
我在这里错过了什么?
答案 0 :(得分:2)
据我所知,你发布的代码绝对没有错。
但是,考虑到您仅在摘录中提供的XML,并且未显示</questions>
结束标记,我怀疑某处q
元素可能缺少answer
属性。