我有一个 svg 模板,我正在复制和自定义它来为游戏创建多个不同的卡片和图 block 。我想以编程方式(最好是在 Python 中)更改每张卡片模板中的元素。我似乎很容易找到更改属性或 css 的方法,但我很难找到一个可以轻松解析现有 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>
我看过 Python 的 lxml
和 xml.dom.minidom
但它们似乎都不支持类似 tile_text_element.innerHTML = "New Tile Name"
。帮忙?
编辑:
为了补充一点我的工作流程,我为每张卡片创建了一堆个性化的 svg,然后通过 inkscape 将它们批量渲染为 pdf。
最佳答案
另一种方法是使用 lxml,似乎可行,警告质量差的代码:
$ 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>
关于python - 在 Python 中替换 SVG 的内部内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726528/