Python - Elementtree - 使用变量在树中搜索

时间:2014-07-29 15:56:29

标签: python xml elementtree

我有这个xml文件,它有很多化学基团及其属性。这是文件的一部分:

 <groups>
  <group name='CH3'>
   <mw>15.03502</mw>
   <heatCapacity>
    <a>19.5</a>
   </heatCapacity>
  </group>
  <group name='CH2'>
   <mw>14.02708</mw>
   <heatCapacity>
    <a>-0.909</a>
   </heatCapacity>
  </group>
  <group name='COOH'>
   <mw>45.02</mw>
   <heatCapacity>
    <a>-24.1</a>
   </heatCapacity>
   </heatCapacity>
  </group>
  <group name='OH'>
   <mw>17.0073</mw>
   <heatCapacity>
    <a>25.7</a>
   </heatCapacity>
  </group>
<\groups>

在我使用ElementTree解析此文件的python代码中,我有一个列表 blocks = ['CH3','CH2']我想用它来找到这两个组。我尝试了以下方法:

import elementtree.ElementTree as ET
document = ET.parse( 'groups.xml' )
blocks=['CH3','CH2']
for item in blocks:
   group1 = document.find(item)
   print group1

我得到的只是'无'。你能帮我吗?

非常感谢

2 个答案:

答案 0 :(得分:2)

试试这个:

for block in blocks:
    group = document.find('./group[@name="{}"]'.format(block))
    if group:
        xml.etree.ElementTree.dump(group)
    else:
        print "Group {} not found.".format(group)

答案 1 :(得分:2)

您可以通过.get()方法找到元素的属性。这是一种看待那里的方法:

import xml.etree.ElementTree as ET
document = ET.parse( 'groups.xml' )
blocks=['CH3','CH2']
for group in document.getroot():
   if group.get('name') in blocks:
     print group

如果您需要通过任意选择条件访问数据,您可以创建自己的字典:

import xml.etree.ElementTree as ET

# Parse
document = ET.parse( 'groups.xml' )

# Add a dictionary so that <group>s
# are easy to find by name
groups = {}
for group in document.getroot():
   groups[group.get('name')] = group

# Look up our compounds in the dictionary
blocks=['CH3', 'CH2']
for item in blocks:
    group = groups[item]
    mw = group.find('mw').text
    print item, mw