使用 pyKML 检查和解析 KML

res*_*ing 7 python kml pykml

与此类似:使用 Python 从 KML BatchGeo 文件中提取坐标

但我想知道如何检查数据对象,以及如何对其进行迭代,并解析所有Placemark以获取coordinates.

下面是 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>
Run Code Online (Sandbox Code Playgroud)

这就是我所拥有的,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
Run Code Online (Sandbox Code Playgroud)

这将打印第一个coordinates.

一般python问题:
如何检查doc、了解其类型并打印出它包含的值?

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

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

for e in doc.Document.Folder.iter('Placemark'):
   print e
Run Code Online (Sandbox Code Playgroud)

res*_*ing 11

我找到了答案。

解析Placemark,这是代码

for e in doc.Document.Folder.Placemark:
  coor = e.Point.coordinates.text.split(',')
Run Code Online (Sandbox Code Playgroud)

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

不知道为什么findall()iter()但没有用:

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

for e in doc.Document.Folder.iter('Placemark'):
Run Code Online (Sandbox Code Playgroud)

两者都空着返回。

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

doc.findall('.//{http://www.opengis.net/kml/2.2}Placemark')
Run Code Online (Sandbox Code Playgroud)