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

xmlstarlet: create an attribute if it does not exist and edit it otherwise

我想使用 xmlstarlet 查找包含属性 inkscape:label="L2" 的 xml 文件的元素并设置其属性 "style" 到值 "display.inline"。困难在于属性 "style" 可能已定义也可能未定义。

我目前正在使用这个命令:

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">

有没有办法在属性不存在时创建属性,否则就进行编辑?

您可以同时使用 --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