Search code examples
xmlxpathantxmltask

xmltask test existence of node without text or attribute


I'm using Ant 1.8.4 and xmltask 1.16. I'm trying to modify Maven pom.xml files to check if there is a /project/properties element and create one if there isn't (so that I can then add a child element). The xmltask documentation indicates I have to use the copy task to check, and then use the if attribute on the insert task. But using this code

<xmltask source="${pomdir}/pom.xml" dest=""${pomdir}/pom.xml">
  <copy path="/:project/:properties" property="hasProperties"/>
  <insert path="/:project/:packaging" position="after" if="hasProperties"
    xml="&lt;properties&gt;"/>
</xmltask>

Produces this warning when there is an existing /project/properties node

Can only copy/cut text() nodes and attribute values to properties (found com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl)

And it inserts a second properties node. Adding "/text()" to the end of the xpath in the copy task gets rid of the warning but doesn't fix the duplicated properties node in the output.


Solution

  • I found the solution. I have to conditionally select the project node that does not have a properties child node.

    <insert path="/:project[not(:properties)]/:packaging"
        position="after">
        <![CDATA[
        <properties>
            <customProperty>blah</customProperty>
        </properties>
        ]]>
    </insert>
    <insert path="/:project/:properties"
        xml="&lt;customProperty&gt;blah&lt;/customProperty&gt;"/>
    

    The first insert covers input files that have no properties, and the second insert covers input files that do already have properties.