如何使用et tree python从xml获取所有子级的子值。 这是相同的数据
<try>
<place>
<c>place of the city <c>
</place>
<details>
<sex> male or female </sex>
<phone> phone no </phone>
<addresses>
<address>
<code>
<areacode> 91 </areacode>
</code>
<peraddr> the great city </peraddr>
</address>
<address>
<code>
<areacode> 9110 </areacode>
</code>
<peraddr> the great wall </peraddr>
</address>
</addresses>
</details>
</try>
如何获取所有区域代码和peraddr值。
答案 0 :(得分:3)
如果没有提供基本代码,有很多方法可以实现这一点。以下是一种可能的方法,首先查找所有address
元素,然后从每个areacode
打印peraddr
和address
值:
>>> raw = '''your xml string here'''
...
>>> from xml.etree import ElementTree as ET
>>> root = ET.fromstring(raw)
>>> for address in root.findall('.//address'):
... print address.find('.//areacode').text, address.find('./peraddr').text
...
91 the great city
9110 the great wall