Skip to main content
 首页 » 编程设计

python之使用 Python 从 XML 中提取值

2025年05月04日12wuhuacong

我从另一个 xml 文件中提取了以下 xml。

<notifications> 
  <notification name="ccmSmtp" oid="1.3.6.1" status="current"> 
    <objects> 
      <object module="callhome" name="ccmSmtp" /> 
    </objects> 
    <description>This is a description</description> 
  </notification> 
  <notification name="ccmAlertGroup" oid="1.3.6.1" status="current"> 
    <objects> 
      <object module="callhome" name="callHome" /> 
    </objects> 
    <description>This is a description</description> 
  </notification> 
  <notification name="ccmAlert" oid="1.3.6.1" status="current"> 
    <objects> 
      <object module="callhome" name="callHome" /> 
    </objects> 
    <description>This is a description</description> 
  </notification> 
  <notification name="ccmSmtp" oid="1.3.6.1" status="current"> 
    <objects></objects> 
    <description>This is a description</description> 
  </notification> 
</notifications> 

我正在使用以下 Python 代码。

from xml.dom import minidom 
 
xmldoc = minidom.parse('example.xml') 
grammarNode = xmldoc.childNodes[2] 
notificationsNode = grammarNode.childNodes[9] 
print notificationsNode.toxml() 

这段 python 代码给出了我上面给出的 xml 的输出。

我尝试了以下方法来获取属性值

notificationlist = xmldoc.getElementsByTagName('notification') 
print notificationlist[0].toxml() 
notification1 = notificationlist[0] 
key = notification1.attributes.keys() 

使用它我只能获得第一组通知的值。

我如何获取属性的所有值并将其存储在单独的变量中?

请您参考如下方法:

如果要获取notificationlist中每一项的属性,你可以这样做:

attrslist = [dict(node.attributes.items()) for node in notificationlist] 
print attrslist[0] 
# => {u'status': u'current', u'oid': u'1.3.6.1', u'name': u'ccmSmtp'} 
print attrslist[0]['status'] 
# => current 

从这里开始,只需迭代这个新列表并按名称为每个 <notification> 提取属性即可。 notificationlist 中的元素.

for n in attrslist: 
   status = n['status'] 
   oid = n['oid'] 
   name = n['name'] 
   # blah