【问题标题】:Error when parsing attributes with python minidom使用 python minidom 解析属性时出错
【发布时间】:2013-05-04 15:41:01
【问题描述】:

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

我在这里错过了什么?

【问题讨论】:

    标签: python python-2.7 minidom


    【解决方案1】:

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

    但是,考虑到您提供的 XML 只是一个摘录,并且没有显示 &lt;/questions&gt; 结束标记,我怀疑某处可能有一个 q 元素缺少 answer 属性。

    【讨论】:

    • nah - 它在第一个问题上出现错误,因为我在每个 q 之后打印出来
    • 哈......我是个骨头。你说的对。这发生在我的第二个条目上。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2020-08-28
    • 2017-09-22
    • 2018-10-23
    • 1970-01-01
    • 2015-05-31
    相关资源
    最近更新 更多