-1

I am trying to extract coordinates from kml file in python but it is giving me the error. below are my code and kml file.

Code:

from pykml import parser

root = parser.fromstring(open('task_2_sensor.kml', 'r').read())
print (root.Document.Placemark.Point.coordinates)

Error:

ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

KML File:

                        <coordinates>
                            13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.310096,52.4893,0 13.310096,52.4893,0 13.309909,52.48929,0 13.309909,52.48929,0 13.309753,52.489235,0                            
                        </coordinates>
                    </LineString>
                </Placemark>
                                        
        </Folder>
                
        <LookAt>
            
        </LookAt>
    </Document>
</kml>
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75

2 Answers2

0

If source KML has an explicit encoding then you must either remove the XML declaration line from the KML or use parse() not fromstring().

Use this form to parse KML file using pykml.

with open('task_2_sensor.kml', 'r') as f:
    root = parser.parse(f).getroot()
print(root.Document.Placemark.Point.coordinates)
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
0

Checking the kml file of the question, this file corresponds to the linestring. In this case, you can use the following lines to get the coordinates of all your points and export them to a file:

from pykml import parser

kml_file = 'myfile.kml'

with open(kml_file, mode='r', encoding='utf-8') as f:
   root = parser.parse(f).getroot()

mycoor = (root.Document.Placemark.LineString.coordinates).text
print(mycoor, file=open('coordinates.txt', mode='w', encoding='utf-8'))
Luke Solo
  • 195
  • 1
  • 1
  • 7