Read kml file with multiple placemarks in pykml

别来无恙 提交于 2019-12-30 10:29:40

问题


In pykml, I can read the first placemark in a file using the following code:

 with open(filename) as f:
     pm = parser.parse(f).getroot().Document.Folder
     print "got :"
     print pm.Placemark.LineString.coordinates

How can I read multiple placemarks in the same file into python?


回答1:


Edit: An even easier solution, assuming all placemarks are in one folder:

from pykml import parser

with open(filename) as f:
  folder = parser.parse(f).getroot().Document.Folder

for pm in folder.Placemark:
  print(pm.name)

You can also use features of the underlying xml library lxml to search for placemark elements.

from pykml import parser
from pykml.factory import nsmap

namespace = {"ns": nsmap[None]}

with open(filename) as f:
  root = parser.parse(f).getroot()
  pms = root.findall(".//ns:Placemark", namespaces=namespace)

  for pm in pms:
    print(pm.name)

If you specifically search for placemarks that have a Linestring child, you can also use xpath for more sophisticated searches.

pms = root.xpath(".//ns:Placemark[.//ns:LineString]", namespaces=namespace)



回答2:


This works:

with open(filename) as f:
    doc = parser.parse(f).getroot().Document.Folder
for pm in doc.iterchildren():
    if hasattr(pm, 'LineString'):
        print pm.LineString.coordinates


来源:https://stackoverflow.com/questions/33321223/read-kml-file-with-multiple-placemarks-in-pykml

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