I was trying to edit an xml file using xmlstarlet in a bash script.
But I found I have a problem when trying to give different values to the same attributes in the same nodes, let me show you with this example:
Using this code
xmlstarlet ed -L -s /foo -t elem -n bar -v "" -i //bar -t attr -n id -v bar1 $file
xmlstarlet ed -L -s /foo -t elem -n bar -v "" -i //bar -t attr -n id -v bar2 $file
using this i get the following result in $file:
<foo>
<bar id="bar1" id="bar2"/>
<bar id="bar2"/>
</foo>
But what I am trying to achieve looks like this:
<foo>
<bar id="bar1"/>
<bar id="bar2"/>
</foo>
Could you help me please?
With this file:
<foo>
</foo>
Command:
xmlstarlet edit --omit-decl \
--subnode "//foo" --type elem -n "bar" \
--insert "//bar[1]" --type attr -n "id" --value "bar1" \
--subnode "//foo" --type elem -n "bar" \
--insert "//bar[2]" --type attr -n "id" --value "bar2" file.xml
If you don't want to count new elements use last()
:
xmlstarlet edit --omit-decl \
--subnode "//foo" --type elem -n "bar" \
--insert "//bar[last()]" --type attr -n "id" --value "bar1" \
--subnode "//foo" --type elem -n "bar" \
--insert "//bar[last()]" --type attr -n "id" --value "bar2" file.xml
Output in both cases:
<foo>
<bar id="bar1"/>
<bar id="bar2"/>
</foo>