首页 > 解决方案 > 从 KML (Python) 中删除元素

问题描述

我使用 Python 的 SimpleKML 库和以下脚本生成了一个 KML 文件,其输出也如下所示:

import simplekml
kml = simplekml.Kml()
ground = kml.newgroundoverlay(name='Aerial Extent')
ground.icon.href = 'C:\\Users\\mdl518\\Desktop\\aerial_image.png'
ground.latlonbox.north = 46.55537
ground.latlonbox.south = 46.53134
ground.latlonbox.east = 48.60005
ground.latlonbox.west = 48.57678
ground.latlonbox.rotation = 0.090320 
kml.save(".//aerial_extent.kml")

输出 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">
    <Document id="1">
        <GroundOverlay id="2">
            <name>Aerial Extent</name>
            <Icon id="3">
                <href>C:\\Users\\mdl518\\Desktop\\aerial_image.png</href>
            </Icon>
            <LatLonBox>
                <north>46.55537</north>
                <south>46.53134</south>
                <east>48.60005</east>
                <west>48.57678</west>
                <rotation>0.090320</rotation>
        </LatLonBox>
    </GroundOverlay>
</Document>

但是,我试图从这个 KML 中删除“文档”标签,因为它是使用 SimpleKML 生成的默认元素,同时保留子元素(例如 GroundOverlay)。此外,有没有办法删除与特定元素关联的“id”属性(即对于 GroundOverlay、Icon 元素)?我正在探索使用 ElementTree/lxml 来启用此功能,但这些似乎更特定于 XML 文件而不是 KML。这是我试图用来修改 KML 的内容,但它无法删除 Document 元素:

from lxml import etree
tree = etree.fromstring(open("C:\\Users\\mdl518\\Desktop\\aerial_extent.kml").read())
for item in tree.xpath("//Document[@id='1']"):
    item.getparent().remove(item)

print(etree.tostring(tree, pretty_print=True))

这是最终所需的输出 XML:

<?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">
    <GroundOverlay>
         <name>Aerial Extent</name>
         <Icon>
             <href>C:\\Users\\mdl518\\Desktop\\aerial_image.png</href>
         </Icon>
         <LatLonBox>
              <north>46.55537</north>
              <south>46.53134</south>
              <east>48.60005</east>
              <west>48.57678</west>
              <rotation>0.090320</rotation>
         </LatLonBox>
    </GroundOverlay>
</kml>

任何见解都非常感谢!

标签: pythonxmlautomationgiskml

解决方案


你被可怕的命名空间绊倒了......

尝试使用这样的东西:

ns = {'kml': 'http://www.opengis.net/kml/2.2'}
for item in tree.xpath("//kml:Document[@id='1']",namespaces=ns):
    item.getparent().remove(item)

编辑:

要仅删除父级并保留其所有后代,请尝试以下操作:

retain = doc.xpath("//kml:Document[@id='1']/kml:GroundOverlay",namespaces=ns)[0]
for item in doc.xpath("//kml:Document[@id='1']",namespaces=ns):
    anchor = item.getparent()
    anchor.remove(item)
    anchor.insert(1,retain)

print(etree.tostring(doc, pretty_print=True).decode())

这应该会为您提供所需的输出。


推荐阅读