2

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.

CodeMonkey
  • 22,825
  • 4
  • 35
  • 75

1 Answers1

1

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
FriC
  • 786
  • 10
  • 14
  • The document has many 'placemark' tags with random 'Point' and 'Polygon' tags inside it. –  Jul 10 '15 at 22:10
  • I am getting an error like "Start tag expected, '<' not found, line 1, column 1". Did i miss something? –  Jul 10 '15 at 22:32
  • That appears to be an error with kml document itself. Is there some tag in the kml that is missing its opening left angle bracket? – FriC Jul 10 '15 at 22:36
  • Is there a way to find all Placemark tags from the document? –  Oct 01 '15 at 23:06