Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding and replacing XML/SVG element text by id with Python's lxml?

I'm new to XML and lxml and would like to use SVG as graphics template and programatically replace some elements (labels in the image). For this, I have created an SVG file with Inkscape, however, lxml seems not to be able to handle the svg:namespaces used by Inkscape. Saving as plain SVG works:

from lxml import etree
ifilename = "ifile.svg"
with open( ifilename, 'r') as infile: 
    tree = etree.parse( infile )
print tree.xpath("//text[@id='findme']/tspan/text()")

But I am not sure whether xpath is the right method to find an element at any position in the element tree!? I'd appreciate a nudge in the right direction.

like image 772
moileroi Avatar asked Dec 12 '25 15:12

moileroi


1 Answers

You should be able to use

print tree.xpath("//n:text[@id='findme']/n:tspan/text()",
                 namespaces={'n': "http://www.w3.org/2000/svg"})

If it doesn't work, please show us the SVG markup. I'm not sure what you mean by "saving as plain SVG works".

like image 145
mzjn Avatar answered Dec 14 '25 08:12

mzjn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!