replacing inner contents of an svg in python

  • Last Update :
  • Techknowledgy :

Another way is to use lxml, seems to work, WARNING bad quality code:

$ cat card.py
#!/usr/bin/env python

from lxml import etree

with open('card.svg') as card:
    root = etree.fromstring(card.read())

root.find('.//{http://www.w3.org/2000/svg}text').text = "foobar"
print etree.tostring(root)
$ python card.py
<svg xmlns="http://www.w3.org/2000/svg" width="181" height="181">
    <text id="tile_text" y="90" width="100%" style="text-align:center;font-family:Verdana;font-size:20">foobar</text>
</svg>

You can do with ETXPath or just XPath, but here a possible way:

from lxml import etree

SVGNS = u"http://www.w3.org/2000/svg"
svg = '''<!--Square 2" Tile Template -->
<svg xmlns="http://www.w3.org/2000/svg" width="181" height="181">
    <text id="tile_text" y="90" width="100%" 
          style="text-align:center;font-family:Verdana;font-size:20">
        TEXT TO REPLACE
    </text>
</svg>'''

xml_data = etree.fromstring(svg)
# We search for element 'text' with id='tile_text' in SVG namespace
find_text = etree.ETXPath("//{%s}text[@id='tile_text']" % (SVGNS))
# find_text(xml_data) returns a list
# [<Element {http://www.w3.org/2000/svg}text at 0x106185ab8>]
# take the 1st element from the list, replace the text
find_text(xml_data)[0].text = 'BLAHBLAH'
new_svg = etree.tostring(xml_data)
print new_svg

Then the result.

<svg xmlns="http://www.w3.org/2000/svg" width="181" height="181">
   <text id="tile_text" y="90" width="100%" style="text-align:center;font-family:Verdana;font-size:20">BLAHBLAH</text>
</svg>

So you may use

<!--Square 2" Tile Template -->
<svg xmlns="http://www.w3.org/2000/svg" width="181" height="181">
   <text id="tile_text" y="90" width="100%" style="text-align:center;font-family:Verdana;font-size:20" content-value="param(label)">default</text>

and use:

your.svg ? label = New Tile Name
>>> root = etree.Element("root")
>>> root.text = "TEXT"

>>> print(root.text)
TEXT

>>> etree.tostring(root)
b'<root>TEXT</root>'

Suggestion : 2

An SVG interpreter is a program which can parse and process SVG document fragments. Examples of SVG interpreters are server-side transcoding tools or optimizer (e.g., a tool which converts SVG content into modified SVG content) or analysis tools (e.g., a tool which extracts the text content from SVG content, or a validity checker).,The context permits giving a context of already set values that are come from outside the current svg context, such as we would find if we had SVG files embedded into SVG files.,Another important SVG elements are the shapes. While all of these can be converted to paths. They can serve some usages in their original form. There are methods to deform a rectangle that simple don't exist in the path form of that object.,The primary goal of this project is to make a more robust version of svg.path to fully parse SVG files. This requires including other elements like Point, Matrix, and Color, etc. with clear emphasis on conforming to the SVG spec in all ways that realworld uses for SVG demands.

The primary function of svgelements is to parse svg files. There are two main functions to facilitate this

    def parse(source,
       reify = True,
       ppi = DEFAULT_PPI,
       width = 1,
       height = 1,
       color = "black",
       transform = None,
       context = None):

Here's an example parser with elements().

       for element in svg.elements():
          try:
          if element.values['visibility'] == 'hidden':
          continue
       except(KeyError, AttributeError):
          pass
       if isinstance(element, SVGText):
          elements.append(element)
       elif isinstance(element, Path):
          if len(element) != 0:
          elements.append(element)
       elif isinstance(element, Shape):
          e = Path(element)
       e.reify() # In some cases the shape could not have reified, the path must.
       if len(e) != 0:
          elements.append(e)
       elif isinstance(element, SVGImage):
          try:
          element.load(os.path.dirname(pathname))
       if element.image is not None:
          elements.append(element)
       except OSError:
          pass

>>> Point(10, 10) * "rotate(90)"
Point(-10, 10)

Suggestion : 3

I have a piece of JavaScript code which creates (using D3.js) an svg element which contains a chart. I want to update the chart based on new data coming from a web service using AJAX, the problem is that each time I click on the update button, it generates a new svg, so I want to remove the old one or update its content.,Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :,How can I remove the old svg element or at least replace its content?,Here is a snippet from the JavaScript function where I create the svg:

Here is a snippet from the JavaScript function where I create the svg:

var svg = d3.select("body")
   .append("svg")
   .attr("width", w)
   .attr("height", h);

Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :

var svg = d3.select("theParentElement").append("svg")
   .attr("id", "the_SVG_ID")
   .attr("width", ...

      ...

      d3.select("#the_SVG_ID").remove();

Suggestion : 4

Last Updated : 30 Jun, 2022

Syntax:

d3.select("element").remove()
  • Using selectAll() Method with remove() Method: The d3.selectAll() method is used to select all the element that matched and remove it. Syntax:
d3.selectAll("element").remove()

Suggestion : 5

Published Apr 06 2018

<svg width="10" height="10">
   <rect x="0" y="0" width="10" height="10" fill="blue" />
</svg>
<img src="image.svg" alt="My SVG image" />
<img src="image.png" alt="My PNG image" />
<img src="image.jpg" alt="My JPG image" />
<img src="image.gif" alt="My GIF image" />
<img src="image.webp" alt="My WebP image" />
<!DOCTYPE html>
<html>

<head>
   <title>A page</title>
</head>

<body>
   <svg width="10" height="10">
      <rect x="0" y="0" width="10" height="10" fill="blue" />
   </svg>
</body>

</html>
<svg>
   <text x="5" y="30">A nice rectangle</text>
</svg>
<svg>
   <circle cx="50" cy="50" r="50" fill="#529fca" />
</svg>