forked from esitarski/CrossMgr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGpxParse.py
48 lines (40 loc) · 1.24 KB
/
GpxParse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import re
import datetime
import xml.sax
reGpxTime = re.compile( '[^0-9+.]' )
class GpxContentHandler( xml.sax.ContentHandler ):
def __init__( self ):
super().__init__()
self.reset()
def reset( self ):
self.fields = {}
self.fieldCur = None
self.trkCount = 0
self.points = []
def startElement( self, name, attr ):
if name in ['trkpt', 'rtept']:
self.fields = {'lat': float(attr.getValue('lat')), 'lon': float(attr.getValue('lon')) }
elif name in ['ele', 'time']:
self.fieldCur = name
elif name == 'trk':
self.trkCount += 1
def characters( self, content ):
if self.fieldCur == 'ele':
self.fields['ele'] = float( content.strip() )
self.fieldCur = None
elif self.fieldCur == 'time':
try:
self.fields['time'] = datetime.datetime( *[int(f) for f in reGpxTime.split(content.strip()) if f] )
except Exception:
pass
self.fieldCur = None
def endElement( self, name ):
if name in ['trkpt', 'rtept'] and self.trkCount <= 1 and 'lat' in self.fields and 'lon' in self.fields:
self.points.append( self.fields )
def GpxParse( fname ):
gpxCH = GpxContentHandler()
xml.sax.parse( fname, gpxCH )
return gpxCH.points
if __name__ == '__main__':
points = GpxParse( 'bugs/GPX/GPXBug.gpx' )
print( points )