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

How to add element and attribute to xml using xmlstarlet?

这是我的 xml:

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

嗯,你可能想先删除//job/file,然后重新添加:

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

是否存在,这都有效