KML to string in Python?

a 夏天 提交于 2020-01-02 20:17:31

问题


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.


回答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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/7821977/kml-to-string-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!