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