import lxml.etree as ET
from copy import deepcopy
xml_source = 'ss_sky_sw_xmltv.xml'
xml_output = 'ss_sky_sw_xmltv_parsed.xml'
# icons with these dimensions (width, height) will be removed:
remove_dimensions = (
(180, 135),
(120, 180),
)
tree = ET.parse(xml_source)
root = tree.getroot()
for programme in root.iterfind('programme'):
# Create copy of all icons to reinsert them in the right order
icons = deepcopy(sorted(programme.findall('icon'), key=lambda x: int(x.attrib['height'])))
# Remove all icons from programme
for old_icon in programme.findall('icon'):
programme.remove(old_icon)
# Reinsert the items
for new_icon in icons:
# Create a dict to compare
dimensions = int(new_icon.attrib['width']), int(new_icon.attrib['height'])
# Compare the dict if it should be removed (not included again)
if dimensions not in remove_dimensions:
programme.append(new_icon)
# Save the file
tree.write(xml_output, xml_declaration=True, pretty_print=True)