Python Minidom-遍历属性并获取其值

Python Minidom-遍历属性并获取其值,python,xml-parsing,minidom,Python,Xml Parsing,Minidom,我有下面的代码试图获取XML中feature属性标记的值 from xml.dom import minidom xmldoc = minidom.parse('P38398.xml') itemlist = xmldoc.getElementsByTagName("feature") for s in itemlist: description = s.attributes['description'].value print description 这个循环给了我以下错误。

我有下面的代码试图获取XML中feature属性标记的值

from xml.dom import minidom
xmldoc = minidom.parse('P38398.xml')
itemlist = xmldoc.getElementsByTagName("feature")
for s in itemlist:
    description = s.attributes['description'].value
    print description
这个循环给了我以下错误。为什么?

Traceback (most recent call last):
File "test.py", line 5, in <module>
description = s.attributes['description'].value
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 522, in __getitem__
return self._attrs[attname_or_tuple]
KeyError: 'description'
回溯(最近一次呼叫最后一次):
文件“test.py”,第5行,在
description=s.attributes['description'].值
文件“/usr/local/ceral/python/2.7.13/Frameworks/python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py”,第522行,在__
返回self.\u attrs[attname\u或\u tuple]
KeyError:“描述”
我做错了什么?任何帮助都将不胜感激。谢谢下面是XML文件

<root>
    <entry>
      <accession>A</accession>
        <feature type="cross-link" description="sumo2">
            <location>
                <position position="15111992"/>
            </location>
        </feature>
        <feature type="cross-link" description="sumo">
            <location>
                <position position="22345"/>
            </location>
        </feature>
    </entry>
    <entry>
      <accession>X</accession>
        <feature type="test" description="testing">
            <location>
                <position position="1"/>
            </location>
        </feature>
        <feature type="cross-link" description="sumo hello">
            <location>
                <position position="11223344"/>
            </location>
        </feature>
    </entry>
</root>

A.
X

在您的代码中,
条目
变量来自哪里?如果您编写
xmldoc.getElementyByTagName
KeyError:“description”
意味着
s.attributes
dict没有带有键
'description'
的条目,那么对我来说就更有意义了。是否检查了所有要素元素在XML中是否都有description属性?如果有,你能上传XML文件的相关部分吗?@AlbertP XML补充道。我用给定的XML运行了你的代码,但它对我有效。四个描述属性打印正确,没有任何错误。我使用的是Python2.7.12,但我认为问题不在于你的版本。看起来这是一个旧线程,但我也运行了这个(v2.7.15),它工作正常。