Quickstart¶
This guide will help you get started with svglab by demonstrating simple usage examples.
Importing the library¶
Start by verifying that the library is installed correctly by importing it in a Python shell or script:
svglab has a flat import structure — this means that all symbols are available directly from the top-level package:
Parsing an SVG file¶
To parse an existing SVG file, use the parse_svg() function. The function returns an Svg object representing the root <svg> element of the document.
Tip
The parse_svg() function can directly read from a file-like object. See the examples below.
Searching for elements¶
Once we have an Svg object, we can obtain a reference to the Circle element by using the find() method.
Modifying attributes¶
Element attributes are represented as properties on the element object. We can modify them directly:
Note
Attribute names that are not valid Python identifiers (e.g. stroke-width) are converted to valid identifiers by replacing hyphens with underscores (e.g. stroke_width). Reserved words are also suffixed with an underscore (e.g. class becomes class_).
Adding new elements¶
New elements can be created by instantiating the corresponding class. The constructor accepts attribute values as keyword arguments. Child elements can be added using the add_child() or add_children() methods.
Serializing the SVG¶
Finally, we can serialize the modified SVG back to a string using the to_xml() method. The resulting string can be saved to a file or used as needed.
Warning
Calling the __str__() method (for example, via print(svg)) will produce a human-readable representation of the object, but it is not valid XML. Always use to_xml() for serialization.
If you want to save the SVG to a file, you can do so as follows: