我有一个 SVG (Xml) 文件,我想从中选择一些元素。为了 MCRE,我已将文件缩减为以下内容
<svg >
<!-- xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" -->
<g>
<path style="fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none" />
<path style="fill:#a80c3d;fill-opacity:1;fill-rule:nonzero;stroke:none" />
<path style="fill:#a98b6e;fill-opacity:1;fill-rule:nonzero;stroke:none" />
</g>
</svg>
根元素的一些可选命名空间属性位于注释中,以便可以将它们插回以复制真实场景(其中 SVG 根元素具有完整属性)。
我想从以下 Xml (SVG) 中选择样式为fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none
。有一场比赛。以下代码适用于给定的 Xml。
from lxml import etree
sFileName = 'C:/Users/Simon/Downloads/pdf_skunkworks/inflation-report-may-2018-page6 - Copy.svg'
tree = etree.Parse(sFileName)
svgNamespace = "xmlns:svg='http://www.w3.org/2000/svg'"
#xpath = r"//svg:path[@style='fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none']"
xpath = r"//path[@style='fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none']"
Print (XPath)
#bluePaths = tree.xpath(xpath,namespaces={ 'svg': svgNamespace })
bluePaths = tree.XPath(XPath)
print (bluePaths[0])
但它适用于给定的 Xml,因为它不具有在真实 SVG 文件中找到的命名空间属性。一旦我重新插入命名空间属性
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" >
然后是Python代码(给出的失败)。我知道我需要使用命名空间,你可以看到我的尝试在 Python 中被注释掉,但它们不起作用。命名空间前缀之一是空字符串,无法传递到命名空间字典。
不管怎样,早上我会写 can 来克隆 SVG 文件并从根元素中删除属性,因为我知道这种方法是有效的。与此同时,如果有人能找到解决这个问题的真正方法,那么我将不胜感激(克隆文件似乎不是最理想的)。
附: SVG 是通过从命令行运行 Inkscape 创建的,我提供了单页 pdf 并要求纯 svg 导出。