【发布时间】:2018-05-11 21:10:07
【问题描述】:
我正在尝试使用 lxml 进行 svg 解析并与命名空间作斗争。
问题:
- 如何使用
tree.iterfind和命名空间映射遍历所有image标签?tree.iterfind('image', root.nsmap)不返回任何东西,更丑的tree.iter('{http://www.w3.org/2000/svg}image')有效 - 我正在尝试将
image标签转换为use标签。虽然 lxml 给了我一个带有xlinx:href的属性字典,但它在将它传递给makeelement时会窒息,有没有优雅的解决方案? - 我应该使用
lxml还是有更好的方法(更直接)?我的目标是将image标签重写为use标签并将引用的svgs 的内容嵌入符号中。 (到目前为止,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)))
【问题讨论】:
标签: python python-3.x lxml