Minidom - 遍历属性并获取其值

时间:2017-04-26 06:50:49

标签: python xml-parsing minidom

我有以下代码尝试获取XML中的要素属性标记的值;

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'

我在这里做错了什么?任何帮助将不胜感激。谢谢。下面是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>

0 个答案:

没有答案