【发布时间】:2017-08-24 13:39:55
【问题描述】:
我有一个具有以下结构的 KML 文件:
<?xml version="1.0"?><kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>Test KML</name>
<description><![CDATA[<p>This is a test version.</p>]]></description>
<Style id="spstyle7">
<IconStyle>
<color>ff4DF6D8</color>
<Icon><href>http://maps.google.com/mapfiles/kml/paddle/wht-blank.png</href></Icon>
</IconStyle>
<LineStyle>
<color>ff4DF6D8</color>
<width>4</width>
</LineStyle>
</Style>
<Folder>
<name>Track1</name>
<visibility>0</visibility>
<name>Test1</name>
<description><![CDATA[test1]]></description>
<Placemark>
<name>test1</name>
<description><![CDATA[test1]]></description>
<MultiGeometry>
<LineString>
<tessellate>true</tessellate>
<altitudeMode>clampToGround</altitudeMode>
<coordinates>
11.000,4.000 11.000,3.000
</coordinates>
</LineString>
<LineString>
<tessellate>true</tessellate>
<altitudeMode>clampToGround</altitudeMode>
<coordinates>
11.000,4.000 12.000,4.000
</coordinates>
</LineString>
<LineString>
<tessellate>true</tessellate>
<altitudeMode>clampToGround</altitudeMode>
<coordinates>
12.000,5.000 12.000,4.000
</coordinates>
</LineString>
</MultiGeometry>
</Placemark>
</Folder>
<Style id="spstyle7">
<IconStyle>
<color>ff4DF6D8</color>
<Icon><href>http://maps.google.com/mapfiles/kml/paddle/wht-blank.png</href></Icon>
</IconStyle>
<LineStyle>
<color>ff4DF6D8</color>
<width>4</width>
</LineStyle>
</Style>
<Folder>
<name>Track2</name>
<visibility>0</visibility>
<name>Test2</name>
<description><![CDATA[test2]]></description>
<Placemark>
<name>test2</name>
<description><![CDATA[test2]]></description>
<MultiGeometry>
<LineString>
<tessellate>true</tessellate>
<altitudeMode>clampToGround</altitudeMode>
<coordinates>
8.000,8.000 8.000,7.000
</coordinates>
</LineString>
<LineString>
<tessellate>true</tessellate>
<altitudeMode>clampToGround</altitudeMode>
<coordinates>
8.000,7.000 11.000,6.000
</coordinates>
</LineString>
<LineString>
<tessellate>true</tessellate>
<altitudeMode>clampToGround</altitudeMode>
<coordinates>
9.000,1.000 10.000,1.000
</coordinates>
</LineString>
</MultiGeometry>
</Placemark>
</Folder>
</Document>
</kml>
我想获取 coordinates 标记内的所有坐标,将其放入列表或列表列表(每个文件夹一个)。
一开始,我写了以下代码:
import xml.etree.ElementTree as ET
tree = ET.parse("test.kml")
root = tree.getroot()
results = root.findall('Folder')
textnumbers = [r.find('Placemark/LineString/coordinates').text for r in results]
print textnumbers
但它返回一个空列表。如果我尝试仅获取 Folder 名称,请使用以下代码:
for folder in root.findall('Folder'):
name = folder.find('name')
print name
我也得到一个空字符串。为什么解析器找不到 Folder 标签?有什么提示吗?
提前感谢您提供的任何帮助。
【问题讨论】:
-
@Wondercricket ...这是不明智的。不必为 XML 解析删除命名空间。
-
我看不到命名空间与我的问题有什么关系。
-
这正是你的问题,因为你有一个带有未声明前缀的命名空间,但不用于解析,因此没有结果!
-
当然,我没有注意它。谢谢!
-
您是否从文档中删除了命名空间?如果有命名空间,您可以轻松读取 XML