Python SVG parser Python SVG parser python python

Python SVG parser


Ignoring transforms, you can extract the path strings from an SVG like so:

from xml.dom import minidomdoc = minidom.parse(svg_file)  # parseString also existspath_strings = [path.getAttribute('d') for path                in doc.getElementsByTagName('path')]doc.unlink()


Getting the d-string can be done in a line or two using svgpathtools.

from svgpathtools import svg2pathspaths, attributes = svg2paths('some_svg_file.svg')

paths is a list of svgpathtools Path objects (containing just the curve info, no colors, styles, etc.). attributes is a list of corresponding dictionary objects storing the attributes of each path.

To, say, print out the d-strings then...

for k, v in enumerate(attributes):    print v['d']  # print d-string of k-th path in SVG


The question was about extracting the path strings, but in the end the line drawing commands were wanted. Based on the answer with minidom, I added the path parsing with svg.path to generate the line drawing coordinates:

#!/usr/bin/python3# requires svg.path, install it like this: pip3 install svg.path# converts a list of path elements of a SVG file to simple line drawing commandsfrom svg.path import parse_pathfrom svg.path.path import Linefrom xml.dom import minidom# read the SVG filedoc = minidom.parse('test.svg')path_strings = [path.getAttribute('d') for path                in doc.getElementsByTagName('path')]doc.unlink()# print the line draw commandsfor path_string in path_strings:    path = parse_path(path_string)    for e in path:        if isinstance(e, Line):            x0 = e.start.real            y0 = e.start.imag            x1 = e.end.real            y1 = e.end.imag            print("(%.2f, %.2f) - (%.2f, %.2f)" % (x0, y0, x1, y1))