使用pyKML解析KML文档

10
我将使用pyKML模块从给定的KML文件中提取坐标。
我的Python代码如下:
from pykml import parser
fileobject = parser.fromstring(open('MapSource.kml', 'r').read())
root = parser.parse(fileobject).getroot()
print(xml.Document.Placemark.Point.coordinates)

然而,运行此代码时,我遇到了以下错误:
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

在寻找解决方案时,我发现了这个解决方案http://twigstechtips.blogspot.in/2013/06/python-lxml-strings-with-encoding.html,我尝试了这个方法(但我不确定是否正确):

from pykml import parser
from lxml import etree
from os import path
kml_file = open('MapSource.kml', 'r')
parser = etree.XMLParser(recover=True)
xml = etree.fromstring(kml_file, parser)
print(xml.Document.Placemark.Point.coordinates)

我遇到了ValueError: can only parse strings的错误。请问我应该如何正确地解析KML并获取该结构中的坐标?


问题可能与您尝试解析的特定KML文件有关。您能否将KML文件发布到公共位置,以便其他人可以尝试复制您遇到的问题? - Tyler Erickson
@TylerErickson,这是您需要的链接:https://raw.githubusercontent.com/SiddharthMantri/TFTSEnhance/master/MapSource.kml - Newtt
1个回答

2
在上面的例子中,root = parser.parse(fileobject).getroot() 调用了 parse() 方法来解析从前一行的 fromstring() 函数返回的字符串形式的文件内容。
使用 pyKML 解析 KML 文件有两种方法:
1:使用 parse.parse() 解析文件。
from pykml import parser
with open('MapSource.kml', 'r') as f:
  root = parser.parse(f).getroot()
print(root.Document.Placemark.Point.coordinates)

2:使用parse.parsestring()函数来解析字符串内容。

from pykml import parser
with open('MapSource.kml', 'rb') as f:
  s = f.read()
root = parser.fromstring(s)
print(root.Document.Placemark.Point.coordinates)

如果KML文件的第一行是非UTF8编码的XML prolog标头,并且尝试使用'r'作为文本格式而不是二进制格式读取文件,则方法#2可能会失败。

请注意,如果在KML文档中错误地指定了编码,则解析可能会失败。以下示例中使用ISO-8859-1编码,因为名称和描述中有国际字符和图形字符。省略编码或使用"UTF-8"将使其成为无效的XML文件。

<?xml version="1.0" encoding="ISO-8859-1"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
  <Placemark>
    <name>Río Grande</name> 
    <description>
      Location: 18° 22′ 49″ N, 65° 49′ 53″ W
    </description>
    ...
</kml>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接