使用et-tree-python从xml中获取子级的子值

2024-09-29 23:31:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用ettreepython从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值。你知道吗


Tags: thecityaddressaddressesphonecodeplacexml
1条回答
网友
1楼 · 发布于 2024-09-29 23:31:54

由于没有提供基本代码,有很多方法可以实现这一点。下面是一种可能的方法,它首先查找所有address元素,然后从每个address打印areacodeperaddr值:

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

相关问题 更多 >

    热门问题