如何通过Ant Task修改XML文件中指定上下文参数的取值
I get it—your current Ant target is wiping out all param-value entries because the XPath path isn't specific enough. Let's fix that to target only the csrf.protection.active parameter.
The Problem with Your Current Target
Your existing XPath /web-app/context-param/param-value/text() doesn't filter which context-param to modify—it matches every single param-value under every context-param in the file. That's why all values get replaced.
The Fix: Targeted XPath with Namespace Handling
First, your web-app uses the Java EE namespace (http://xmlns.jcp.org/xml/ns/javaee), so we need to define that namespace in XMLTask to make the XPath work correctly. Then we'll add a condition to only select the context-param where param-name equals csrf.protection.active.
Here's the updated 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"> <!-- Map the Java EE namespace to a prefix (we'll use "jee" here) --> <namespace uri="http://xmlns.jcp.org/xml/ns/javaee" prefix="jee"/> <!-- XPath to target ONLY the param-value for csrf.protection.active --> <replace path="/jee:web-app/jee:context-param[jee:param-name='csrf.protection.active']/jee:param-value/text()" withText="true"/> </xmltask> </target>
Breakdown of the Updated XPath
Let's break down what this XPath does:
/jee:web-app: Starts at the rootweb-appnode (using our namespace prefix)/jee:context-param[jee:param-name='csrf.protection.active']: Filterscontext-paramnodes to only those where the childparam-namehas the exact textcsrf.protection.active/jee:param-value/text(): Targets the text content of theparam-valueunder that specificcontext-param
This way, only the param-value linked to csrf.protection.active gets updated—all other context parameters stay untouched. Just adjust the withText value to whatever you need (like true in the example above).
内容的提问来源于stack exchange,提问作者Gihan Saranga Siriwardhana

