Search code examples
xmlxml-parsingxmlstarlet

How to add and/or subtract a constant from some XML element values with xmlstarlet


I have an XML file with lots of entries like the following:

<object>
    <name>buf</name>
    <bndbox>
        <xmin>535</xmin>
        <ymin>725</ymin>
        <xmax>636</xmax>
        <ymax>821</ymax>
    </bndbox>
</object> 

Is there a way to use xmlstarlet (or another tool) to subtract the value of 10 from each xmin element's current value?


Solution

  • To subtract the value of 10 from all xmin elements, use the following xmlstarlet command:

    xmlstarlet ed -u "//xmin" -x ".-10" input.xml
    

    Output of the sample XML is:

    <?xml version="1.0" encoding="UTF-8"?>
    <ParentId>
      <object>
        <name>buf</name>
        <bndbox>
          <xmin>525</xmin>
          <ymin>725</ymin>
          <xmax>636</xmax>
          <ymax>821</ymax>
        </bndbox>
      </object>
    </ParentId>