Search XML tag by value between them and insert new tag in script shell

Let's say I have this test.xml file that contains this data

<d> <p> <n>hi</n> <r> <s>1.0</s> </r> </p> <p> <n>hello</n> <r> <s>1.0</s> </r> </p> </d> 

I want to add a new <s> 2.0 </s> for the hello object as shown below.

 <d> <p> <n>hi</n> <r> <s>1.0</s> </r> </p> <p> <n>hello</n> <r> <s>1.0</s> <s>2.0</s> </r> </p> </d> 

I need to do this using a shell script. There is a way to search through the XML DOM and add tags using xmlstarlet given here http://www.technomancy.org/xml/add-a-subnode-command-line-xmlstarlet/ . But this only describes adding a new tag to specific nodes based on the attribute value. I have no attributes. How can I do it? Is there any way to do this with grep?

0
source share
1 answer
 xmlstarlet ed -a '//p[n="hello"]/r/s' -t elem -ns -v 2.0 input.xml 

Explanation:

  • ed ==> edit
  • -a ==> add
  • -t ==> type
  • -n ==> name
  • -v ==> value
+3
source

All Articles