Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##This script allows the batch repair of corrupted .tcx activity files.
- ##Create backups before use and use script at own risk.
- ##License: GPLv3
- import os
- import xml.etree.ElementTree as ET
- def prettify(elem, level=0):
- #Add indentation to the XML element
- indent = " "
- i = "\n" + level * indent
- if len(elem):
- if not elem.text or not elem.text.strip():
- elem.text = i + indent
- if not elem.tail or not elem.tail.strip():
- elem.tail = i
- for sub_elem in elem:
- prettify(sub_elem, level + 1)
- if not sub_elem.tail or not sub_elem.tail.strip():
- sub_elem.tail = i
- else:
- if level and (not elem.tail or not elem.tail.strip()):
- elem.tail = i
- def convert_tomtom_to_garmin(xml_content):
- root = ET.fromstring(xml_content)
- # Update namespace
- ET.register_namespace('', 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2')
- ET.register_namespace('xsi', 'http://www.w3.org/2001/XMLSchema-instance')
- ET.register_namespace('x', 'http://www.garmin.com/xmlschemas/ActivityExtension/v2')
- # Add indentation to the XML structure
- prettify(root)
- # Convert the XML tree to a string
- converted_xml = ET.tostring(root, encoding="utf-8").decode("utf-8")
- return converted_xml
- def convert_all_files(input_folder, output_folder):
- # Create output folder if it doesn't exist
- os.makedirs(output_folder, exist_ok=True)
- # Iterate through each file in the input folder
- for filename in os.listdir(input_folder):
- if filename.endswith(".tcx"):
- input_path = os.path.join(input_folder, filename)
- output_path = os.path.join(output_folder, filename)
- convert_tomtom_to_garmin_and_save(input_path, output_path)
- def convert_tomtom_to_garmin_and_save(input_path, output_path):
- with open(input_path, 'r', encoding="utf-8") as file:
- # Read all lines
- lines = file.readlines()
- # Remove leading whitespace from the first line
- if lines:
- lines[0] = lines[0].lstrip()
- xml_content = ''.join(lines)
- converted_xml = convert_tomtom_to_garmin(xml_content)
- # Check if the XML declaration is present
- if not converted_xml.startswith('<?xml'):
- # Add the XML declaration if not present
- converted_xml = f'<?xml version="1.0" encoding="UTF-8"?>\n{converted_xml}'
- with open(output_path, 'w', encoding="utf-8") as file:
- file.write(converted_xml)
- if __name__ == "__main__":
- input_folder_path = './input'
- output_folder_path = './converted'
- convert_all_files(input_folder_path, output_folder_path)
Advertisement
Add Comment
Please, Sign In to add comment