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

如何使用xmlstarlet向xml添加元素和属性?

  •  0
  • rodee  · 技术社区  · 6 年前

    $ cat job.xml 
    <job>
       <file> </file>
    </job>
    

    我正在添加一个属性,这很有效。

    $ xmlstarlet edit --omit-decl --inplace --insert '//job/file' --type 'attr'\
    -n 'type' --value 'text' --update '//job/file' --value file.txt job.xml\
    $ cat job.xml 
    <job>
       <file type="text">file.txt</file>
    </job>
    
    
    #Running again, this time I want it to replace if attribute is already present.
    
    $ xmlstarlet edit --omit-decl --inplace --insert '//job/file' --type 'attr'\
    -n 'type' --value 'bin' --update '//job/file' --value file.bin job.xml\
    $ cat job.xml 
    <job>
      <file type="text" type="bin">file.bin</file>
    </job>
    

    我想要 <file type="bin">file.bin</file> <file type="text" type="bin">file.bin</file> 这一次。

    此外,我喜欢添加元素,即使它根本不存在,例如:

    <job>
    </job>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   glenn jackman    6 年前

    嗯,您可能要先删除//job/文件,然后重新添加它:

    xmlstarlet edit --omit-decl \
        --delete  '//job/file' \
        --subnode '//job'      --type elem --name file --value file.bin \
        --insert  '//job/file' --type attr --name type --value bin \
      job.xml
    

    不管是否存在//job/file,这都会起作用