如何使用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
相关产品推荐
相关产品推荐

