You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PYKML提取KML文件中gx:LatLonQuad下的coordinates内容

用PYKML提取KML中gx:LatLonQuad下的coordinates内容

处理带gx:前缀的节点时,核心是正确处理命名空间——gx是KML的扩展命名空间,以下是具体实现步骤:

步骤1:导入依赖并读取KML文件

先导入PYKML解析模块,读取目标KML文件:

from pykml import parser

# 替换为你的KML文件实际路径
with open("your_kml_file.kml", "r", encoding="utf-8") as f:
    kml_doc = parser.parse(f).getroot()

步骤2:定位节点并提取内容

KML默认命名空间与gx扩展命名空间均为http://www.google.com/kml/ext/2.2,可通过两种方式提取coordinates内容:

方法一:XPath直接定位

# 定义命名空间映射
ns = {"gx": "http://www.google.com/kml/ext/2.2"}

# 提取文本并去除多余空白字符
coords_text = kml_doc.xpath("//gx:LatLonQuad/coordinates", namespaces=ns)[0].text.strip()

print(coords_text)

方法二:逐层遍历节点

如果需要更精细的节点控制,可逐层查找:

ns = {"gx": "http://www.google.com/kml/ext/2.2"}

# 定位GroundOverlay节点
ground_overlay = kml_doc.find(".//{http://www.google.com/kml/ext/2.2}GroundOverlay")
# 定位gx:LatLonQuad节点
latlon_quad = ground_overlay.find("gx:LatLonQuad", namespaces=ns)
# 提取coordinates内容
coords_text = latlon_quad.find("{http://www.google.com/kml/ext/2.2}coordinates").text.strip()

print(coords_text)

两种方法最终输出结果一致:

9.2703219809,56.2281778343 9.2930588405,56.2281260725 9.2931273404,56.2370979805 9.2703851665,56.2371497598

内容的提问来源于stack exchange,提问作者Stig Barrett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:18:42