Python和lxml:从给定元素中获取子子元素

时间:2014-05-19 20:59:34

标签: python xml lxml

我有这个XML代码:

<ProceduresDB>
  <Airport ICAOcode="EHRD">
    <Sid Name="ANDI1A" Runways="06">
      <Sid_Waypoint ID="1">
        <Latitude>0.000000</Latitude>
        <Longitude>0.000000</Longitude>
      </Sid_Waypoint>
      <Sid_Waypoint ID="2">
        <Latitude>51.973697</Latitude>
        <Longitude>4.480970</Longitude>
      </Sid_Waypoint>
    <Sid Name="ARNE2A" Runways="06">
      <Sid_Waypoint ID="1">
      etc etc

我如何获得Sid Name='ANDI1A'的每个航路点的所有纬度和经度?

我一直在尝试使用lxml来提出一些东西,但大多数教程/ howto确实涵盖了嵌套子代的XML文档。

1 个答案:

答案 0 :(得分:1)

您可以使用.//Sid[@Name="ANDI1A"]/Sid_Waypoint xpath表达式:

import lxml.etree as ET

data = """<ProceduresDB>
  <Airport ICAOcode="EHRD">
    <Sid Name="ANDI1A" Runways="06">
      <Sid_Waypoint ID="1">
        <Latitude>0.000000</Latitude>
        <Longitude>0.000000</Longitude>
      </Sid_Waypoint>
      <Sid_Waypoint ID="2">
        <Latitude>51.973697</Latitude>
        <Longitude>4.480970</Longitude>
      </Sid_Waypoint>
    </Sid>
   </Airport>
</ProceduresDB>"""

tree = ET.fromstring(data)
for waypoint in tree.findall('.//Sid[@Name="ANDI1A"]/Sid_Waypoint'):
    print "Waypoint %s" % waypoint.attrib["ID"]
    for item in waypoint:
        print item.tag, item.text

打印:

Waypoint 1
Latitude 0.000000
Longitude 0.000000
Waypoint 2
Latitude 51.973697
Longitude 4.480970