获取子对象';使用et-tree-python从xml中提取子值
如何使用et-tree-python从xml中获取所有子级的子值。 这是同样的数据获取子对象';使用et-tree-python从xml中提取子值,python,xml,python-2.7,xml-parsing,elementtree,Python,Xml,Python 2.7,Xml Parsing,Elementtree,如何使用et-tree-python从xml中获取所有子级的子值。 这是同样的数据 <try> <place> <c>place of the city <c> </place> <details> <sex> male or female </sex> <phone> phone no </phone>
<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>
城址
男还是女
电话号码
91
大城市
9110
长城
如何获取所有区号和peraddr值。由于没有提供基本代码,有许多方法可以实现这一点。下面是一种可能的方法,它首先查找所有
地址
元素,然后从每个地址
打印区域代码
和peraddr
值:
>>> 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
值:
>>> 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语法,顺便说一句,
/
用于子元素,/
用于子元素。有关其他地址,请参阅文档。查找('peraddr')。文本(完全没有/
)也将被删除work@louis当然,不客气!怎么样谢谢你能解释一下为什么peraddr使用单“/”吗?@louis这是XPath语法,顺便说一句,/
表示子元素,/
表示子元素。有关其他地址,请参阅文档。查找('peraddr')。文本(完全没有/
)也将被删除work@louis当然,不客气!怎么样谢谢