2012-12-10 63 views
4

我正在生成旨在包含Inkscape特定標籤的SVG文件。例如,inkscape:labelinkscape:groupmode。我使用lxml etree作爲我的分析器/生成器。我想在labelgroupmode標籤添加到以下實例:python lxml inkscape命名空間標籤

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

我的問題是我怎麼做到這一點,以獲得在SVG正確的輸出格式,例如:

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

回答

9

首先,記住inkscape:心不是」命名空間,它指的是在你的XML根元素定義的命名空間的一種簡便方法。命名空間是http://www.inkscape.org/namespaces/inkscape,根據您的XML,inkscape:groupmode可能與foo:groupmode相同。當然,您的<g>元素是SVG命名空間http://www.w3.org/2000/svg的一部分。

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中的屬性添加,你可以這樣做:要生成LXML合適的輸出,你會像這樣的東西開始

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=參數來清理命名空間標籤。就像這樣:

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) 

有了這個地方,最後的結果將是這樣的:在LXML documentation

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

更多信息。

+0

作品!感謝您的詳細解答。 –