Question

So I'm trying to write a program (with no dependencies) that will read a KML file from Google Maps (see below) to get just the coordinates and store them in a Matrix for later data manipulation.

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
  <name>Driving directions to Commercial St/A1202</name>
  <description><![CDATA[]]></description>
  <Style id="style1">
    <IconStyle>
      <Icon>
        <href></href>
      </Icon>
    </IconStyle>
  </Style>
  <Style id="style2">
    <LineStyle>
      <color>73FF0000</color>
      <width>5</width>
    </LineStyle>
  </Style>
  <Style id="style3">
    <IconStyle>
      <Icon>
        <href></href>
      </Icon>
    </IconStyle>
  </Style>
  <Placemark>
    <name>From: Unknown road</name>
    <styleUrl>#style1</styleUrl>
    <Point>
      <coordinates>-0.168942,51.520180,0.000000</coordinates>
    </Point>
  </Placemark>
  <Placemark>
    <name>Driving directions to Commercial St/A1202</name>
    <styleUrl>#style2</styleUrl>
    <ExtendedData>
      <Data name="_SnapToRoads">
        <value>true</value>
      </Data>
    </ExtendedData>
    <LineString>
      <tessellate>1</tessellate>
      <coordinates>
        -0.168942,51.520180,0.000000
        -0.167752,51.520447,0.000000
        -0.167371,51.520481,0.000000
      </coordinates>
    </LineString>
  </Placemark>
  <Placemark>
    <name>To: Commercial St/A1202</name>
    <styleUrl>#style3</styleUrl>
    <Point>
      <coordinates>-0.073247,51.516960,0.000000</coordinates>
    </Point>
  </Placemark>
</Document>
</kml>

While this isn't inefficient for small files like the one above, I have 500+KB files to parse later! So any suggestions on efficient ways (which don't involve "non standard" imports that require installing) of just getting these coordinates and storing them as a Matrix?

Was it helpful?

Solution

So, the following should do you. By dependencies I assume you mean outside of the standard library that comes with Python (I'm not sure how you would have a python install without the standard library tbh)....

import xml.etree.ElementTree as ET

print 'Starting'

tree = ET.parse('sample_data.xml')
root = tree.getroot()

for child in root.findall('.//{http://earth.google.com/kml/2.2}coordinates'):
    print child.text

If you really can't use ElementTree then you've got bigger problems than the efficiency of your XML processing.

As an aside...two minutes (or less) of googling would have got you to this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top