Search code examples
bashxmlstarlet

Delete xml elements with multiple criteria in xmlstarlet


I am trying to write a bash script to delete xml element with multiple criteria.

For example:

<a>
 <b>
  <name>x</name>
  <age>15</age>
  <group>maths</group>
  <grade>A</grade>
 </b>
 <b>
  <name>x</name>
  <age>14</age>
  <group>maths</group>
  <grade>B</grade>
 </b>
 <b>
  <name>y</name>
  <age>15</age>
  <group>maths</group>
  <grade>C</grade>
 </b>
</a>

Here I need to delete the xml element having values name = x and age = 15

Expected output:

<a>
 <b>
  <name>x</name>
  <age>14</age>
  <group>maths</group>
  <grade>B</grade>
 </b>
 <b>
  <name>y</name>
  <age>15</age>
  <group>maths</group>
  <grade>C</grade>
 </b>
</a>

The below element should be deleted.

 <b>
  <name>x</name>
  <age>15</age>
  <group>maths</group>
  <grade>A</grade>
 </b>

Solution

  • If you are using xmlstarlet, try:

    xmlstarlet ed -d '//b[name="x"][age="15"]' file.xml