1

I'd like to download a KML file and print a particular element of it as a string in Python.

Could anyone give me an example of how to do this?

Thanks.

Richard
  • 31,629
  • 29
  • 108
  • 145

3 Answers3

1

Downloading and parsing I'll leave to the other answer. Here's how I retrieved the description and coordinates for each placemark in a KML file.

namespace = {'ns' : 'http://www.opengis.net/kml/2.2'}
placemarks = doc.xpath('//ns:Placemark', namespaces=namespace)

for placemark in placemarks :
    for description in placemark.xpath('.//ns:description', namespaces=namespace):
        descriptionText = description.text.strip()

    for coords in placemark.xpath('.//ns:coordinates', namespaces=namespace):
        coordinates = coords.text.strip()

    # Here you have the description and coordinates

The for loops for the description and coordinates could perhaps be rewritten, but I haven't found exactly how yet.

ramdyne
  • 177
  • 1
  • 9
0

Google's new pyKML library is good for this. See e.g. pyKML Examples

Here is a very simple example from http://packages.python.org/pykml/tutorial.html

import urllib2
from pykml import parser

url = 'http://code.google.com/apis/kml/documentation/KML_Samples.kml'
fileobject = urllib2.urlopen(url)
root = parser.parse(fileobject).getroot()
print root.Document.name
nealmcb
  • 12,479
  • 7
  • 66
  • 91
0

You can download the KML file in python using urllib. For reading KML, you can use a parser (search for "kml python parser").

amit kumar
  • 20,438
  • 23
  • 90
  • 126