Search code examples
shellxmlstarlet

How to add element and attribute to xml using xmlstarlet?


Here is my xml:

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

I am adding an attribute, this works.

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

I want <file type="bin">file.bin</file> instead of <file type="text" type="bin">file.bin</file> this time.

Also, I like to add element even if its not present at all, e.g:

<job>
</job>

Solution

  • Hmm, you might want to first delete //job/file, then re-add it:

    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
    

    That would work regardless of the presence of //job/file