Skip to content

Instantly share code, notes, and snippets.

@kk7ds
Created April 15, 2019 01:24
Show Gist options
  • Save kk7ds/5fcd255360365842d07f71f16b67cdfd to your computer and use it in GitHub Desktop.
Save kk7ds/5fcd255360365842d07f71f16b67cdfd to your computer and use it in GitHub Desktop.
#!/usr/bin/python
#
# Copyright 2019 Dan Smith <dsmith+gist@danplanet.com>
#
# This fixes broken Gaia GPX files which fail to pass the GPX 1.1 schema
# check (and thus won't import into real software) because the elements
# are ordered incorrectly.
#
# Run me like this:
#
# python gpx_order.py broken_gaia_file.gpx fixed_gaia_file.gpx
#
import collections
import itertools
import os
import sys
import xml.etree.ElementTree as ET
ET.register_namespace('', "http://www.topografix.com/GPX/1/1")
try:
input_fn = sys.argv[1]
except IndexError:
print('Usage: %s INPUT_FILE [OUTPUT_FILE]' % (
os.path.basename(sys.argv[0])))
sys.exit(1)
try:
output_fn = sys.argv[2]
except IndexError:
output_fn = 'new_%s' % input_fn
tree = ET.parse(input_fn)
root = tree.getroot()
# Find all the elements
elements = collections.defaultdict(list)
for child in root:
print(child.tag)
elements[child.tag].append(child)
# Remove them all from the tree
for child in itertools.chain.from_iterable(elements.values()):
root.remove(child)
# Add them back in the proper order
for etype in ('metadata', 'wpt', 'rte', 'trk', 'extensions'):
etype = '%s%s' % ('{http://www.topografix.com/GPX/1/1}', etype)
print('Adding %i %s elements' % (len(elements[etype]), etype))
for element in elements[etype]:
root.append(element)
print('Writing %s' % output_fn)
tree.write(output_fn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment