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

3
我希望使用xmlstarlet来查找一个包含inkscape:label="L2"属性的XML文件元素,并将其属性“style”设置为值"display.inline"。困难在于属性“style”可能已经被定义,也可能没有被定义。
我目前正在使用以下命令:
xmlstarlet edit --inplace --update "//*[@inkscape:label=\"L2\"]/@style" --value "display:inline" ex.svg 

如果style属性已经定义,它将起作用。
// 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个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接