Python - Elementtree - search a tree using a variable

I have this xml file that contains many chemical groups and their properties. Here is a snippet of the file:

 <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>

In my python code that parses this file using ElementTree, I have a list of blocks = ['CH3', 'CH2'] and I want to use this to find two groups. I tried the following:

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

And all I get is No. Can you help me?

Many thanks

+4
source share
2 answers

You can find the attributes of the elements through your method .get(). Here is one way to look there:

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
+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)
+2

All Articles