xmlstarlet:创建一个属性(如果它不存在),否则编辑它

时间:2017-12-14 09:36:20

标签: xml xpath attributes xmlstarlet

我想使用xmlstarlet查找包含属性inkscape:label =“L2”的xml文件的元素,并将其属性“style”设置为值“display.inline”。难点在于属性“样式”可能已经定义,也可能尚未定义。

我目前正在使用此命令:

xmlstarlet edit --inplace --update "//*[@inkscape:label=\"L2\"]/@style" --value "display:inline" ex.svg 

如果已经定义了属性样式,它将起作用

// It works on this
<g inkscape:groupmode="layer"
 id="layer2"
 inkscape:label="L2"
 style="display:none">

但不会起作用:

// Does not work
<g inkscape:groupmode="layer"
 id="layer2"
 inkscape:label="L2">

我还定义了一个能够添加所需属性的命令:

xmlstarlet ed --insert "//*[@inkscape:label=\"L2\"]" --type attr -n style -v "display:inline" ex.svg > output.svg

不幸的是,如果该属性已存在,则会添加第二个属性:

// The element now contains two attributes style
<g inkscape:groupmode="layer"
 id="layer2" 
 inkscape:label="L2" 
 style="display:none" 
 style="display:inline">

有没有办法创建属性,如果它不存在,否则编辑它?

1 个答案:

答案 0 :(得分:2)

您可以同时使用--update--insert,但只能在元素没有style属性(not(@style))时插入。

示例:

xmlstarlet edit --inplace --update "//*[@inkscape:label=\"L2\"]/@style" --value "display:inline" --insert "//*[@inkscape:label=\"L2\"][not(@style)]" --type attr -n style -v "display:inline" ex.svg
相关问题