[英]Python - ElementTree Library - Search through tree by attribute value
[英]Python - Elementtree - Search through tree using a variable
我有这个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代码中,我有一个list 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
我得到的只是'无'。 你能帮我么?
非常感谢
试试这个:
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)
您可以通过其.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.