2

我的 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'

我在这里想念什么?

4

1 回答 1

2

据我从您发布的代码中可以看出,绝对没有错。

但是,考虑到您仅在摘录中提供的 XML,并且没有显示</questions>结束标记,我怀疑某处可能存在缺少属性的q元素。answer

于 2013-05-04T16:03:05.593 回答