How to insert subnode in xml file using xmlstarlet or any other bash command?

I have multiple xml files where i want to update a subnode if the subnode project points to different project or insert a subnode if it doesn't exist using a xmlstarlet or any other command that can be used in a bash script.

I have been able to update the subnode project if it doesn't point to the right project using xml starlet command, but i am not able to insert subnode project if the project tag doesn't exist.

I have tried.

xmlstarlet ed -P --update "///module[@id='pxc110237_1']/@project" -v"X1" --insert"///module[@id='pxc110237_1']/@project --type attr -n style -v"X1" file.xml

The file looks like:

 <?xml version="1.0"?>
  <kgcontent>
    <containers>
       <module project="ANY" level="1" id="pxc110233_1"/>
       <module project="X1" level="1" id="pxc110234_1"/>
       <module id="pxc110235_1"/>
    </containers>
  <kgcontent>

I want the output to look like:

<?xml version="1.0"?>
  <kgcontent>
    <containers>
       <module project="ANY" level="1" id="pxc110233_1"/>
       <module project="X1" level="1" id="pxc110234_1"/>
       <module project="X1" id="pxc110235_1"/>
    </containers>
  <kgcontent>

The starlet command i used doesn't have any effect on the file. how can i fix the above problem? any pointers would be great help :slight_smile:

Linux distrubution: SUSE
Shell: Bash

Thank you!

1 Like

You can easily use sed to accomplish this, if I understand your question correctly.

I suggest you try to use sed to accomplish this and post the code you wrote / tried and the results.