Saa*_*mer 4 python svg lxml inkscape
我正在生成一个SVG文件,该文件旨在包含特定于Inkscape的标记.例如,inkscape:label
和inkscape:groupmode
.我使用lxml etree作为我的解析器/生成器.我想将label
和groupmode
标签添加到以下实例:
layer = etree.SubElement(svg_instance, 'g', id="layer-id")
Run Code Online (Sandbox Code Playgroud)
我的问题是如何实现这一点,以便在SVG中获得正确的输出形式,例如:
<g inkscape:groupmode="layer" id="layer-id" inkscape:label="layer-label">
Run Code Online (Sandbox Code Playgroud)
首先,请记住,这inkscape:
不是一个命名空间,它只是一种引用XML根元素中定义的命名空间的便捷方式.命名空间是http://www.inkscape.org/namespaces/inkscape
,并且取决于您的XML,inkscape:groupmode
可能与之相同foo:groupmode
.当然,您的<g>
元素是SVG名称空间的一部分http://www.w3.org/2000/svg
.要使用LXML生成适当的输出,您可以从以下内容开始:
from lxml import etree
root = etree.Element('{http://www.w3.org/2000/svg}svg')
g = etree.SubElement(root, '{http://www.w3.org/2000/svg}g', id='layer-id')
Run Code Online (Sandbox Code Playgroud)
哪能得到你:
<ns0:svg xmlns:ns0="http://www.w3.org/2000/svg">
<ns0:g id="layer-id"/>
</ns0:svg>
Run Code Online (Sandbox Code Playgroud)
要添加特定于inkscape的属性,您可以这样做:
g.set('{http://www.inkscape.org/namespaces/inkscape}groupmode', 'layer')
g.set('{http://www.inkscape.org/namespaces/inkscape}label', 'layer-label')
Run Code Online (Sandbox Code Playgroud)
哪能得到你:
<ns0:svg xmlns:ns0="http://www.w3.org/2000/svg">
<ns0:g xmlns:ns1="http://www.inkscape.org/namespaces/inkscape" id="layer-id" ns1:groupmode="layer" ns1:label="layer-label"/>
</ns0:svg>
Run Code Online (Sandbox Code Playgroud)
信不信由你想要的是什么.您可以通过nsmap=
在创建根元素时传递参数来稍微清理命名空间标签.像这样:
NSMAP = {
None: 'http://www.w3.org/2000/svg',
'inkscape': 'http://www.inkscape.org/namespaces/inkscape',
}
root = etree.Element('{http://www.w3.org/2000/svg}svg', nsmap=NSMAP)
Run Code Online (Sandbox Code Playgroud)
有了这个,最终输出将如下所示:
<svg xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns="http://www.w3.org/2000/svg">
<g id="layer-id" inkscape:label="layer-label" inkscape:groupmode="layer"/>
</svg>
Run Code Online (Sandbox Code Playgroud)
LXML文档中的更多信息.
归档时间: |
|
查看次数: |
1572 次 |
最近记录: |