Vanaan
Vanaan

Reputation: 69

xmlstarlet update attribute value if it exists or create a line with the attribute

I have xml format as shown below. I want to add new line with <property name="xxx">5</property> to the below xml under same node. If this line already exists it should update only the attribute value or else it has to insert new line with attribute and its value.

<book>
   <property name="abc">3</property>
   <property name="xyz">2</property>
</book>

I used following command to update if exists or it creates new one if it doesn't exist

xmlstarlet edit -L \
-u "/book/property[@name=xxx]" -v '5' \
-i "/book/property[not(@name=xxx]" --type attr -n "xxx" -v '5' \
book.xml

the output should be like

  <book>
       <property name="abc">3</property>
       <property name="xyz">2</property>
       <property name="xxx">5</property>
    </book>

But my output is different and it is adding the attr in the existing lines like as below

<book>
   <property name="abc" zzz=5>3</property>
   <property name="xyz" zzz=5>2</property>
</book>

can anyone help me on this?

Upvotes: 0

Views: 586

Answers (1)

Vanaan
Vanaan

Reputation: 69

yes, iam using bash script to do it. Anyways i got this and i used as below in my script. It worked.

xmlstarlet ed -L --subnode "//book" --type elem -n property -v "" \
--insert "/book/property[3]" --type attr -n "name" -v "zzz" \
--update "/book/property[@name=zzz]" -v "5" \
book.xml

Upvotes: 1

Related Questions