python lxml inkscape名称空间标签 [英] python lxml inkscape namespace tags

查看:116
本文介绍了python lxml inkscape名称空间标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成一个SVG文件,该文件旨在包含Inkscape特定的标签.例如,inkscape:labelinkscape:groupmode.我正在使用lxml etree作为解析器/生成器.我想将labelgroupmode标记添加到以下实例:

I am generating an SVG file that's intended to include Inkscape-specific tags. For example, inkscape:label and inkscape:groupmode. I am using lxml etree as my parser/generator. I'd like to add the label and groupmode tags to the following instance:

layer = etree.SubElement(svg_instance, 'g', id="layer-id")

我的问题是如何实现这一点,以便在SVG中获得正确的输出格式,例如:

My question is how do I achieve that in order to get the correct output form in the SVG, for example:

<g inkscape:groupmode="layer" id="layer-id" inkscape:label="layer-label">

推荐答案

首先,请记住inkscape:不是名称空间,它只是引用XML根元素中定义的名称空间的便捷方法.名称空间为http://www.inkscape.org/namespaces/inkscape,根据您的XML,inkscape:groupmode可能与foo:groupmode相同.当然,您的<g>元素是SVG命名空间http://www.w3.org/2000/svg的一部分.要使用LXML生成适当的输出,您将从以下内容开始:

First, remember that inkscape: isnt' a namespace, it's just a convenient way of referring to a namespace that is defined in your XML root element. The namespace is http://www.inkscape.org/namespaces/inkscape, and depending on your XML, inkscape:groupmode might be identical to foo:groupmode. And of course, your <g> element is part of the SVG namespace, http://www.w3.org/2000/svg. To generate appropriate output with LXML, you would start with something like this:

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')

哪位可以帮助您:

<ns0:svg xmlns:ns0="http://www.w3.org/2000/svg">
  <ns0:g id="layer-id"/>
</ns0:svg>

要添加特定于inkscape的属性,请执行以下操作:

To add in the inkscape-specific attributes, you would do this:

g.set('{http://www.inkscape.org/namespaces/inkscape}groupmode', 'layer')
g.set('{http://www.inkscape.org/namespaces/inkscape}label', 'layer-label')

哪位可以帮助您:

<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>

信不信由你.您可以在创建根元素时通过传递nsmap=参数来稍微清理名称空间标签.像这样:

Which believe it or not is exactly what you want. You can clean up the namespace labels a bit by passing an nsmap= parameter when creating your root element. Like this:

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)

安装好之后,最终输出将如下所示:

With this in place, the final output would look like this:

<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>

LXML文档中的更多信息.

这篇关于python lxml inkscape名称空间标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆