How to add diferent attributes to each node of an xmlfile using xmlstarlet

橙三吉。 提交于 2019-11-28 06:30:38

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/48061266/how-to-add-diferent-attributes-to-each-node-of-an-xmlfile-using-xmlstarlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!