xmlstarlet:如果属性不存在则创建该属性,否则对其进行编辑

Zac*_*ach 2 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 
Run Code Online (Sandbox Code Playgroud)

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

// It works on this
<g inkscape:groupmode="layer"
 id="layer2"
 inkscape:label="L2"
 style="display:none">
Run Code Online (Sandbox Code Playgroud)

但它不会工作,否则:

// Does not work
<g inkscape:groupmode="layer"
 id="layer2"
 inkscape:label="L2">
Run Code Online (Sandbox Code Playgroud)

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

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

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

// The element now contains two attributes style
<g inkscape:groupmode="layer"
 id="layer2" 
 inkscape:label="L2" 
 style="display:none" 
 style="display:inline">
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*ley 6

您可以同时使用--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
Run Code Online (Sandbox Code Playgroud)