【问题标题】:fetch child's child value from xml using et tree python使用et tree python从xml中获取孩子的孩子值
【发布时间】:2016-05-16 01:48:35
【问题描述】:

如何使用 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 值。

【问题讨论】:

  • 到目前为止你有没有尝试过?请分享一下

标签: python xml python-2.7 xml-parsing elementtree


【解决方案1】:

在没有提供基本代码的情况下,有很多方法可以实现这一点。下面是一种可能的方法,首先找到所有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 

【讨论】:

  • 您介意解释一下为什么 peraddr 使用单个“/”吗?
  • @louis 这是 XPath 语法,顺便说一句。简单来说,/ 是子元素,// 是子元素。请参阅其他supported XPath syntax的文档
  • address.find('peraddr').text(完全没有/)也可以使用
  • @louis 当然,不客气! accepting the answer 怎么样?谢谢
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2014-10-16
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多