8

与此类似:Extract Coordinates from KML BatchGeo File with Python

但我想知道如何检查数据对象,以及如何迭代它,并解析所有Placemarkcoordinates.

下面是 KML 的样子,有多个<Placemark>标签。

示例 KML 数据

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.opengis.net/kml/2.2 http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd http://www.google.com/kml/ext/2.2 http://code.google.com/apis/kml/schema/kml22gx.xsd">
<Document id="...">
  <name>...</name>
  <Snippet></Snippet>
  <Folder id="...">
    <name>...</name>
    <Snippet></Snippet>
    <Placemark id="...">
      <name>....</name>
      <Snippet></Snippet>
      <description>...</description>
      <styleUrl>....</styleUrl>
      <Point>
        <altitudeMode>...</altitudeMode>
        <coordinates> 103.xxx,1.xxx,0</coordinates>
      </Point>
    </Placemark>
    <Placemark id="...">
      ...
    </Placemark>
  </Folder>
  <Style id="...">
    <IconStyle>
      <Icon><href>...</href></Icon>
      <scale>0.250000</scale>
    </IconStyle>
    <LabelStyle>
      <color>00000000</color>
      <scale>0.000000</scale>
    </LabelStyle>
    <PolyStyle>
      <color>ff000000</color>
      <outline>0</outline>
    </PolyStyle>
  </Style>
</Document>
</kml>

这就是我所拥有的,extract.py

from pykml import parser
from os import path

kml_file = path.join('list.kml')

with open(kml_file) as f:
  doc = parser.parse(f).getroot()

print doc.Document.Folder.Placemark.Point.coordinates

这将打印第一个coordinates.

一般 python 问题:
我如何检查doc,找出它的类型,并打印出它包含的值?

任务问题:我如何遍历所有Placemark并获得它coordinates

已尝试以下但未打印任何内容。

for e in doc.Document.Folder.iter('Placemark'):
   print e
4

1 回答 1

12

我找到了答案。

解析Placemark,这是代码

for e in doc.Document.Folder.Placemark:
  coor = e.Point.coordinates.text.split(',')

要查找对象类型,请使用type(object).

不知道为什么findall()并且iter()没有工作:

doc.Document.Folder.findall('Placemark')

for e in doc.Document.Folder.iter('Placemark'):

两人都空手而归。

更新:缺少findall工作的命名空间。

doc.findall('.//{http://www.opengis.net/kml/2.2}Placemark')
于 2017-04-04T07:52:20.750 回答