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.
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.
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.
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
You can download the KML file in python using urllib. For reading KML, you can use a parser (search for "kml python parser").