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?

Upvotes: 1

Views: 225

Answers (2)

CAustin
CAustin

Reputation: 4614

It's usually not a good idea to try to parse/edit XML with regex. All you have to do is fix your XPath. The following code will only modify param-value nodes that have sibling param-name nodes containing the text "deployment.type":

    <xmltask source="web.xml" dest="web2.xml" report="true">
        <replace path="/:web-app/:context-param/:param-name[text() = 'deployment.type']/../:param-value/text()" withText="new text"/>
    </xmltask>

Upvotes: 1

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>

Upvotes: 0

Related Questions