'Python SVG remove all tags with specific id attribute

I have an SVG image with Model and Group as ID attribute of tag g, like

<?xml version="1.0"?>
 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="1141.5200729370117" version="1.1" width="1726.9000701904297" id="temp" viewBox="0 0 1726.9000701904297 1141.5200729370117">
  <defs/>
   <g id="Model" class="Model A">
    <g class="Group">
     <g id="Group-1" class="Group A">
       <g id="Line" fill="#000000" stroke="#000000" style="fill-opacity: 1; stroke-opacity: 1; stroke-width: 0.2;" class="Line External"><polygon points="118.00,21.56 1293.38,21.56 1277.38,37.56 133.97,37.56 "/> </g>
       <g id="Box" fill="#FFFFFF" stroke="#FFFFFF" style="fill-opacity: 1; stroke-opacity: 1; stroke-width: 0.2;" class="Box External"><polygon points="118.00,21.56 1293.38,21.56 1277.38,37.56 133.97,37.56 "/> </g>
     </g>
    </g>
  </g>
</svg>

I want to remove all g tags which have id other than Line. I read the SVG file using:

import xml.etree.ElementTree as ET
root = ET.parse('my file.svg')
SVG_NS = "http://www.w3.org/2000/svg"

Then I create a parent map

parent_map = {c:p for p in root.iter() for c in p}

And remove those other than Line

for node in root.findall('.//{%s}g' % SVG_NS):
 name = node.get('id')
 if "Line" in str(name):
    print('n=', node)
 else:
    parent_map[node].remove(node)

How do I convert back the parent_map to an SVG and save it as a png file?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source