在pykml

时间:2015-10-24 17:34:25

标签: python kml

pykml中,我可以使用以下代码读取文件中的第一个地标:

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

如何将同一文件中的多个地标读入python?

2 个答案:

答案 0 :(得分:7)

编辑:一个更简单的解决方案,假设所有地标都在一个文件夹中:

from pykml import parser

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

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

您还可以使用基础xml库lxml的功能来搜索地标元素。

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)

如果您专门搜索具有Linestring子项的地标,您还可以使用xpath进行更复杂的搜索。

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

答案 1 :(得分:6)

这有效:

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