元素树不加载Google Earthexported KML

2024-04-28 20:31:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个与googleearth导出的KML有关的问题,因为它似乎不能很好地与元素树一起工作。我不知道问题出在哪里,所以我会解释我是怎么做的。在

以下是相关代码:

    kmlFile = open( filePath, 'r' ).read( -1 ) # read the whole file as text
    kmlFile = kmlFile.replace( 'gx:', 'gx' )   # we need this as otherwise the Element Tree parser
                                               # will give an error

    kmlData = ET.fromstring( kmlFile )
    document = kmlData.find( 'Document' )

使用这段代码,ET(Element Tree object)创建一个可通过变量kmlData访问的Element对象。它指向根元素('kml'标记)。但是,当我搜索子元素“Document”时,它返回None。虽然KML文件中有'Document'标记!在

除了'gx:smth'标记之外,KMLs和XMLs之间还有其他差异吗?我已经搜查了我正在处理的KML文件,没有发现任何可疑之处。下面是程序要处理的KML文件的简化结构:

^{pr2}$

你知道为什么我不能访问“kml”的任何子元素吗?顺便说一下,Python版本是2.7。在


Tags: 文件the代码标记tree元素readas
1条回答
网友
1楼 · 发布于 2024-04-28 20:31:53

KML文档位于http://earth.google.com/kml/2.2命名空间中,如

<kml xmlns="http://earth.google.com/kml/2.2">

这意味着Document元素的名称实际上是{http://earth.google.com/kml/2.2}Document。在

而不是这样:

^{pr2}$

你需要这个:

document = kmlData.find('{http://earth.google.com/kml/2.2}Document')

但是,XML文件有一个问题。有一个元素叫做gx:altitudeModegx位是名称空间前缀。需要声明这样的前缀,但缺少声明。在

您只需将gx:替换为gx,就解决了这个问题。但正确的方法是添加名称空间声明。基于https://developers.google.com/kml/documentation/altitudemode,我认为gxhttp://www.google.com/kml/ext/2.2名称空间相关联。因此,为了使文档格式良好,根元素起始标记应该为

<kml xmlns="http://earth.google.com/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">

现在可以解析文档:

In [1]: from xml.etree import ElementTree as ET

In [2]: kmlData = ET.parse("kml2.xml")

In [3]: document = kmlData.find('{http://earth.google.com/kml/2.2}Document')

In [4]: document
Out[4]: <Element '{http://earth.google.com/kml/2.2}Document' at 0x1895810>

In [5]:

相关问题 更多 >