我正试图用lxml
进行svg解析,并与名称空间作斗争。
问题:
如何使用image
和namsepace映射遍历所有tree.iterfind
标记?tree.iterfind('image', root.nsmap)
不重新启动任何内容,更丑的tree.iter('{http://www.w3.org/2000/svg}image')
可以工作
我正试图将image
标记转换为use
标记。虽然lxml给了我一个带有xlinx:href
的属性字典,但是它在把这个传递给makeelement
时会感到窒息,是否有一个优雅的解决方案?
我应该使用lxml
还是有更好的方法(更直接)?我的目标是将image
标记重写为use
标记,并将引用svg的内容嵌入到符号中。(到目前为止,lxml
和我的问题与名称空间似乎令人反感)。
.
from lxml import etree
def inlineSvg(path):
parser = etree.XMLParser(recover=True)
tree = etree.parse(path, parser)
root = tree.getroot()
print(root.nsmap)
for img in tree.iter('{http://www.w3.org/2000/svg}image'):
#for img in tree.iterfind('image', root.nsmap): #for some reason I can't get this to work...
print(img)
#we have to translate xlink: to {http://www.w3.org/1999/xlink} for it to work, despit the lib returning xlink: ...
settableAttributes = dict(img.items()) #img.attribute
settableAttributes['{http://www.w3.org/1999/xlink}href'] = settableAttributes['xlink:href']
del settableAttributes['xlink:href']
print(etree.tostring(img.makeelement('use', settableAttributes)))
最佳答案
如何使用tree.iterfind和namsepace映射遍历所有图像标记?
for img in root.iterfind('image', namespaces=root.nsmap):
我正试图将图像标记转换为使用标记。虽然lxml给了我一个带有xlinx:ref的属性字典,但是它在把这个传递给makeelement时会窒息,有没有一个优雅的解决方案?
对我来说这两件事中的一件:
img.makeelement('use', dict(img.items())
img.makeelement('use', img.attrib)
我应该使用lxml还是有更好的方法(更直接)?
每个人都有自己的看法。我喜欢lxml。我觉得很简单。你的意见可能不同。
完整程序:
from lxml import etree
def inlineSvg(path):
parser = etree.XMLParser(recover=True)
tree = etree.parse(path, parser)
root = tree.getroot()
for img in root.iterfind('image', namespaces=root.nsmap):
use = img.makeelement('use', img.attrib, nsmap=root.nsmap)
print(etree.tostring(use))
inlineSvg('xx.svg')
输入文件(
xx.svg
):<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="130" width="500" style="fill: #000000"/>
<image x="20" y="20" width="300" height="80"
xlink:href="http://jenkov.com/images/layout/top-bar-logo.png" />
<line x1="25" y1="80" x2="350" y2="80"
style="stroke: #ffffff; stroke-width: 3;"/>
</svg>
结果:
$ python xx.py
b'<use xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" height="80" width="300" x="20" y="20" xlink:href="http://jenkov.com/images/layout/top-bar-logo.png"/>'
参考:
http://lxml.de/api/lxml.etree._Element-class.html#iterfind
http://tutorials.jenkov.com/svg/image-element.html#svg-image-example