Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...