0
我在同一水平上有两种节点(这里foo
和bar
)的XML文件的工作,像这样:高效的方法来搜索包含节点的xml节点?
<foo>
<id>123</id>
<name>The first foo</name>
</foo>
<foo>
<id>456</id>
<name>The second foo</name>
</foo>
<bar>
<name>The first bar</name>
<foo>123</foo>
</bar>
<bar>
<name>The second bar</name>
<foo>123</foo>
</bar>
需要注意的是:
- 有一个
foo
对于每个bar
; - 有一个或几个
bar
关联到每个foo
。
我想获得,每个bar
,对应foo
节点,所以我写了这个代码:
import xml.etree.ElementTree as ET
root = ET.fromstring(data)
for bar in root.findall('bar'):
for foo in root.findall('foo'):
if foo.find('id').text == bar.find('foo').text:
foo_of_bar = foo
pass
print bar.find('name').text + ': ' + foo_of_bar.find('name').text
结果:
The first bar: The first foo
The second bar: The first foo
但我问自己,如果有是一种更好的方式,使用XPath语法或更多pythonic代码。
什么是ET?你能否显示进口? –
ET for'xml.etree.ElementTree' – roipoussiere
我们在谈论多少个节点?几百或几十万? – Tomalak