我尝试删除ID为#34; area_3"的元素。我使用了类似的东西:
for node in tree.xpath('//ellipse'):
node.getparent().remove(node)
SVG示例:
<svg width="600" height="600" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Created with Method Draw - http://github.com/duopixel/Method-Draw/ -->
<g>
<title>Layer 1</title>
<image id="svg_1" y="0" x="0"/>
<image stroke="null" xlink:href="tehplan.jpg" id="svg_5" height="587.777769" width="585.333339" y="0.578137" x="20.083334"/>
<ellipse ry="19" rx="18" id="area_2" cy="172" cx="189" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000" fill="#ffffff"/>
<ellipse id="area_3" ry="19" rx="18" cy="161" cx="275" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000" fill="#ffffff"/>
</g>
</svg>
答案 0 :(得分:2)
试试这个:
from lxml import etree
tree = etree.parse(open("so.svg"))
to_remove = tree.xpath("/svg:svg/svg:g/svg:ellipse[@id=\"area_3\"]",
namespaces={"svg": "http://www.w3.org/2000/svg"})[0]
g = to_remove.getparent()
g.remove(to_remove)
with open("so.out.svg", "wb") as o:
o.write(etree.tostring(tree, pretty_print=True))
输出:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
<!-- Created with Method Draw - http://github.com/duopixel/Method-Draw/ -->
<g>
<title>Layer 1</title>
<image id="svg_1" y="0" x="0"/>
<image stroke="null" xlink:href="tehplan.jpg" id="svg_5" height="587.777769" width="585.333339" y="0.578137" x="20.083334"/>
<ellipse ry="19" rx="18" id="area_2" cy="172" cx="189" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000" fill="#ffffff"/>
</g>
</svg>