如何使用Ant替换XML字段的值?

时间:2016-03-02 21:20:16

标签: xml ant xmltask

在Ant脚本中,我需要在以下persistence.xml文件中替换javax.persistence.jdbc.url属性的值。

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>org.somecompany.domain.SomeEntity</class>
        <validation-mode>NONE</validation-mode>
        <properties>
            <property name="testprop" value="testval" />
        </properties>
    </persistence-unit>
</persistence>

我已经下载了XMLTask并尝试了以下内容:

<xmltask source="${persistence-xml-file-path}" dest="${persistence-xml-file-path}_replaced" report="true">
    <replace path="/:persistence/:persistence-unit/:properties/:property[:name/text()='testprop']/:value/text()" withText="replaced" />
</xmltask>  

不幸的是,这不起作用。我没有得到任何错误。源和目标xml文件的内容都显示在控制台中,它们是相同的。就好像上面引用的替换指令永远不会运行(或永远不会识别要更新的属性)。

===以下来自Patrice的回应===================================== ==

这似乎可以在没有持久性标记的模式定义的情况下工作:

<xmltask source="${persistence-xml-file-path}" dest="${persistence-xml-file-path}_replaced" report="true" failWithoutMatch="true">
<attr path="persistence/persistence-unit/properties/property[@name='testprop']" attr="value" value="replaced"/>
</xmltask>

这似乎适用于持久性标记的模式定义:

<xmltask source="${persistence-xml-file-path}" dest="${persistence-xml-file-path}_replaced" report="true" failWithoutMatch="true">
<attr path="//*[@name='testprop']" attr="value" value="replaced"/>
</xmltask>

我需要处理的属性非常独特,所以这对我来说很好,而不需要检查整个属性路径。

1 个答案:

答案 0 :(得分:2)

正如@Rao所提到的,你的问题是xpath没有正确处理命名空间。使用“:”的语法对我来说并不一致。正如此站点上显示的许多其他XmlTask​​答案一样,您需要使用//*[local-name()='persistence']语法。 此外,可以使用@name语法引用属性。 最后,如果您要替换属性的值,请不要使用<replace xpath="...,请使用<attr xpath="...

请尝试:

<xmltask source="${persistence-xml-file-path}" dest="${persistence-xml-file-path}_replaced" report="true">
   <attr path="/*[local-name()='persistence']/*[local-name()='persistence-unit']/*[local-name()='properties']/*[local-name()='property'][@name='testprop']" attr="value" value="replaced" />
</xmltask>