Using pyKML to parse KML Document Using pyKML to parse KML Document xml xml

Using pyKML to parse KML Document


In above example, root = parser.parse(fileobject).getroot() is calling parse() on file contents as a string returned from fromstring() function from the previous line.

There are two methods to parse a KML file using pyKML:

1: Using parse.parse() to parse the file.

from pykml import parserwith open('MapSource.kml', 'r') as f:  root = parser.parse(f).getroot()print(root.Document.Placemark.Point.coordinates)

2: Using parse.parsestring() to parse the string contents.

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

Method #2 can fail if the KML file has an XML prolog header as the first line with non-UTF8 encoding and try to read the file with 'r' as text vs 'rb' for binary format.

Note parsing can fail if the encoding is incorrectly specified in the KML document. ISO-8859-1 encoding is used in example below because of the international and graphic characters in the name and description. Omitting the encoding or using "UTF-8" would make it an invalid XML file.

<?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>