anttargetmaven-ant-tasks

Ant task to update xml file when having list of tags


I have an XML file with a set of context parameters.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"   version="3.1">      
    <context-param>
        <param-name>deployment.type</param-name>
        <param-value>main</param-value>
    </context-param>        
    <context-param>
        <param-name>csrf.protection.active</param-name>
        <param-value>false</param-value>
    </context-param>           
</web-app>

I want to update the param-value of csrf.protection.active

I found this ant target.

<target name="update-csrf-value">
    <xmltask source="${dist.dir}/docker/WEB-INF/web.xml" dest="${dist.dir}/docker/WEB-INF/web.xml" report="true">
        <replace path="/:web-app/:context-param/:param-value/text()" withText="new text"/>
    </xmltask>
</target>

But with this, all my parameter values get changed. How can I change the value of a specific key?


Solution

  • Found a workaround. I replaced the whole tag by finding it with regex.

      <target name="update-csrf-value">
        <replaceregexp file="${dist.dir}/docker/WEB-INF/web.xml"
                match="&lt;param-name&gt;csrf.protection.active&lt;/param-name&gt;${line.separator}(\s*)&lt;param-value&gt;([a-z]+)&lt;/param-value&gt;"
                replace="&lt;param-name&gt;csrf.protection.active&lt;/param-name&gt;${line.separator}\1&lt;param-value&gt;false&lt;/param-value&gt;"/>
       </target>