使用lxml选择group by group id的SVG路径

时间:2015-11-16 23:11:28

标签: python svg lxml

我无法使用lxml选择一组特定的路径。 SVG结构看起来像这样

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Created with matplotlib (http://matplotlib.org/) -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="288pt" version="1.1" viewBox="0 0 432 288" width="432pt">
    <defs>
        <style type="text/css">
            *{stroke-linecap:butt;stroke-linejoin:round;}
        </style>
    </defs>
    <g id="figure_1">
        <g id="patch_1">
            <path d=" M0 288 L432 288 L432 0 L0 0 z " style="fill:#ffffff;"/>
        </g>
        <g id="patch_2">
            <path d=" M0 288 L432 288 L432 0 L0 0 z " style="fill:#ffffff;"/>
        </g>
    <g id="axes_1">
        <g id="Poly3DCollection_1">
            <path clip-path="url(#pe61355d493)" d=" M195.211 34.2225 L194.801 34.0894 L196.527 212.986 L196.909 212.999 z " style="fill:#0000ff;"/>
            <path clip-path="url(#pe61355d493)" d=" M195.504 34.3231 L195.211 34.2225 L196.909 212.999 L197.184 213.022 z " style="fill:#0000ff;"/>
...

我想要选择并改变其样式的底部列出的路径但我似乎无法正确使用语法而我无法选择路径

ifilename = "myfig.svg"
with open( ifilename, 'r') as infile: 
tree = etree.parse( infile )

elements = tree.findall(".//g[@id='Poly3DCollection_1'") 
new_style = 'stroke-width:4px; stroke: linear-gradient(orange, darkblue)'

for child in elements:
    child.attrib['style'] = new_style

mod_svg = 'myfigmod.svg'
tree.write(mod_svg)

修改

所以在这个例子中我得到了我想要的元素,但我仍然想要一个特定的方法来获取这个元素

root = tree.getroot()
for child in root[1][2][0]:
    child.attrib['style'] = new_style

1 个答案:

答案 0 :(得分:1)

etree中没有get_element_by_id,所以你必须使用xpath,就像你要抓取元素一样。我创建了你的文件并运行了下面的代码,并且能够改变组的风格。

element = tree.findall(".//{%s}g[@id='Poly3DCollection_1']" % SVG_NS)[0]
element.attrib["style"] = new_style