【问题标题】:Ant task to update xml file when having list of tags具有标签列表时更新 xml 文件的 Ant 任务
【发布时间】:2020-04-18 21:44:49
【问题描述】:

我有一个带有一组上下文参数的 XML 文件。

<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>

我想更新参数值 csrf.protection.active

我找到了这个蚂蚁目标。

<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>

但是有了这个,我所有的参数值都被改变了。如何更改特定键的值?

【问题讨论】:

    标签: ant target maven-ant-tasks


    【解决方案1】:

    找到了解决方法。我用正则表达式替换了整个标签。

      <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>
    

    【讨论】:

      【解决方案2】:

      尝试使用正则表达式解析/编辑 XML 通常不是一个好主意。您所要做的就是修复您的 XPath。以下代码将仅修改具有包含文本“deployment.type”的兄弟param-name 节点的param-value 节点:

          <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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-27
        • 1970-01-01
        • 2011-07-07
        • 1970-01-01
        • 2017-04-17
        相关资源
        最近更新 更多