代码之家  ›  专栏  ›  技术社区  ›  Zach

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

  •  2
  • Zach  · 技术社区  · 7 年前

    我想使用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">
    

    如果属性不存在,是否有方法创建该属性,否则是否有方法对其进行编辑?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Daniel Haley    7 年前

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