pythondjangoparsingkmlpykml

KML parsing child elements using django


I am trying to parse a kml file using django. I am using pyKML Parser Module. I have completed the following steps.

 root = parser.fromstring(open('myfile.kml').read())

The content of the file is:

 <document>
    <Placemark>
      <name>t1</name>
       <Point><coordinates>v1</coordinates>
       </Point>
    </Placemark>
    <Placemark>
     <name>t2</name>
     <Polygon>
       <outerBoundaryIs>
         <LinearRing><coordinates>v2</coordinates>
        </LinearRing>
      </outerBoundaryIs>
    </Polgon>
   </Placemark>
  </document>

I am able to retrieve the names using the following:

name = []

for ele in root.Document.Placemark:
    name.append(ele.name)

But i dont know how the retrieve the coordinates values from different Placemark. Please help me here.


Solution

  • Try this:

    for pm in root.Document.Placemark:
        point = [p for p in pm.getchildren() if p.tag.endswith('Point')]
        if point:
            coords = point[0].coordinates.text
        else:
            poly = [p for p in pm.getchildren() if p.tag.endswith('Polygon')]
            if poly:
                coords = poly[0].outerBoundaryIs.LinearRing.coordinates.text
        print pm.name, coords