Validate KML geometries in python

data validationgeometrykmlpython

I have a CSV file where in a column there are some KML geometries.
These geometries can be points, lines, polygons etc. I would like to validate them and check if they are correctly written.

I'm reading the CSV with Pandas

import pandas as pd
csv = read_csv('file.csv')

#Let's take into account just the first location
coordinates = csv.['location'].loc[0] 

coordinates would be:

<Point><coordinates>2.34880,48.85341</coordinates></Point>

I tried to proceed with fastKML, but it searches for a complete KML file to check and not just the string I got.

So I'm wondering, is there any possibility to validate directly the sting?


Edit: With the tip from @user2856 I manage to check the geometry.

i.e.:

kml_start="<kml xmlns='http://www.opengis.net/kml/2.2'><Placemark><name>Simple placemark</name><description>Test.</description>'"
kml_end = "</Placemark></kml>"
kml_test = kml_start+str(coordinates)+kml_end

try:
    k = kml.KML()
    k.from_string(kml_test)
    print("geometry")
except:
    errors +=1
    print("Error, no Geometry")

Best Answer

Perhaps wrap it into a complete KML string for a simple placemark, then parse it with fastkml from_string:

e.g.

import pandas as pd
csv = read_csv('file.csv')

#Let's take into account just the first location
coordinates = csv.['location'].loc[0] 

kml_template = """
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Placemark>
    <name></name>
    <description></description>
    {}
  </Placemark>
</kml>
"""

k = kml.KML()
k.from_string(kml_template.format(coordinates))
Related Question