1

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>

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.