[英]Add/remove xml field from svg file with bash
我有一组svg图像,我想用bash脚本修改。 特别是,我想通过保留其他路径从图像中删除特定路径。 这是一个有效的例子:
<path
id="rect5505"
d="M 118.34375,20 C ... z"
style="fill:#4d8ecb;stroke:none;fill-opacity:1" />
<path
style="fill:#000000;fill-opacity:0.23529412;stroke:none;display:inline"
d="m ... z"
id="path17954"
sodipodi:nodetypes="ssccccccccccccssccccccs" />
在这种情况下,有两个path
元素,但我想只删除有fill:#000000;fill-opacity:0.23529412
那个fill:#000000;fill-opacity:0.23529412
。 我知道我可以使用sed
来识别包含这些字段的行,但是如何删除整个path
字段?
我想强调一下,这个问题不是使用bash脚本添加/删除xml标签的重复,因为在这种情况下只有一个字段类型。 通过使用类似的东西
sed -i '/<path/,/<\/>/d' image.svg
我会删除文件中的每一个路径,不是吗?
用sed编辑XML并不是一个非常好的主意。 我的建议是使用xmlstarlet
:
xmlstarlet ed -d '//path[contains(@style, "fill:#000000") and contains(@style, "fill-opacity:0.23529412")]' filename.xml
哪里
xmlstarlet ed -d xpath filename.xml
从filename.xml
删除与给定XPath表达式匹配的元素,以及
//path[contains(@style, "fill:#000000") and contains(@style, "fill-opacity:0.23529412")]
是一个XPath表达式,它匹配所有具有包含fill:#000000
的style
属性的path
节点fill:#000000
和fill-opacity:0.23529412
。
附录:由于contains()
执行简单的字符串比较,因此在某些极端情况下,上面使用的XPath表达式可能会产生误报。 例如,如果style
属性包含字符串foo-fill:#000000
,则contains(@style, "fill:#000000")
将为true。 围绕这个特定问题的一种简单但有点笨拙的方法是使用
xmlstarlet ed -d '//path[contains(concat(";", @style, ";"), ";fill:#000000;") and contains(concat(";", @style, ";"), ";fill-opacity:0.23529412;")]' filename.xml
......虽然这仍然留下了空白的问题。 我认为一个完美的解决方案必须解析CSS和XML,这需要做更多的事情(可能还需要Perl)。
附录2:看来我们有名称空间SNAFU 。 要解决这个问题,请使用
xmlstarlet ed -N svg='http://www.w3.org/2000/svg' -d '//svg:path[contains(@style, "fill:#000000") and contains(@style, "fill-opacity:0.23529412")]' accessibility.svg
那是:
xmlstarlet ed -N svg='http://www.w3.org/2000/svg' -d xpath filename
修改xpath
以使用svg:path
而不是path
。 这是必要的,因为有一个属性
xmlns="http://www.w3.org/2000/svg"
在输入文件的svg
标记中,XPath要求处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.