3

I try to parse a KML file to retrieve the polygon names and -coordinates. I try to do this with FastKML (also tried pykml and element.tree, but no result). Reading the KML seems to be good. However, then creating the string to read (and parse), seems to create a problem. I have this code:

from fastkml import kml

with open('Test.kml', 'rt', encoding="utf-8") as myfile:
    doc = myfile.read()

k = kml.KML()
k.from_string(doc)

placemarks = list(innerFeature[0].features())

However, I get this feedback from the terminal:

Traceback (most recent call last):
  File "parse_kml.py", line 17, in <module>
    k.from_string(doc)
  File "/Users/*****/opt/anaconda3/lib/python3.8/site-packages/fastkml/kml.py", line 89, in from_string
    element = etree.fromstring(
  File "src/lxml/etree.pyx", line 3237, in lxml.etree.fromstring
  File "src/lxml/parser.pxi", line 1891, in lxml.etree._parseMemoryDocument
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

I installed the FastKML library with pip. In the past, I also installed some libraries with Anaconda (e.g. GeoPandas) which created some errors during installation. I am now doubting if this error message is caused by a corrupted library system, or if the problem is in my coding.

1 Answer 1

2

It is a pure Python problem (without Gis component). The problem came from the lxml library used by Fastkml (in config.py).

from lxml import etree
data = open('my.kml')
xml_content = data.read()
root = etree.XML(xml_content)
Traceback (most recent call last):
...
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

The solution is given in lxml.etree.XML ValueError for Unicode string and I refer you to the explanation (the error in you script come from encoding="utf-8" )

Therefore, this work:

data = open('my.kml','rb')
xml_content = data.read()
root = etree.XML(xml_content)

And

with open('my.kml','rb') as myfile:
   doc = myfile.read()
k = kml.KML()
k.from_string(doc)
1
  • Many thanks! Very appreciated.
    – GIStrees
    May 20, 2021 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.