bioShark
bioShark

Reputation: 703

Ant XMLTASK insert a node if it doesn't exist already

I have a task to insert an XML node into an existing XML file, only if the node doesn't exist already. I manage the insert just fine, however I can't find that missing if-not functionality

<xmltask source="shared.xml" dest="shared.xml" outputter="simple:3">
   <insert path="/sharedobjects[last()]">
      <![CDATA[
      <connection>   
         <name>MY CONNECTION</name>
      </connection>
      ]]>
   </insert>
</xmltask>

If I run this multiple times, of course I will have multiple MY CONNECTION in the xml file. I would like to make a check so that I insert only if the desired connection is not already in the file.

Thanks in advance.

Upvotes: 6

Views: 6052

Answers (3)

Hans Wouters
Hans Wouters

Reputation: 628

Using Ant conditions (not sure if all existed when the question was asked):

<if>
    <not>
        <resourcecontains 
            resource="shared.xml" 
            substring="&gt;MY CONNECTION&lt;name&gt;" />
    </not>
<then>
    <xmltask 
...
    </xmltask>
</then>

Upvotes: 0

pearcemerritt
pearcemerritt

Reputation: 199

I believe this method works as well.

<xmltask source="shared.xml" dest="shared.xml" outputter="simple:3">

   <copy path="/sharedobjects/connection[name/text()='MY CONNECTION']/name/text()"
         property="XML_EXISTS_ALREADY" />

   <insert path="/sharedobjects[last()]" unless="XML_EXISTS_ALREADY">
      <![CDATA[
      <connection>   
         <name>MY CONNECTION</name>
      </connection>
      ]]>
   </insert>
</xmltask>

NOTE: xmltask's copy task only allows you to store attributes or text nodes in properties. Thus it is necessary to specify /name/text() at the end of the path argument for <copy> (even though the existence we really care about is the whole <connection> node, not its child's text).

Upvotes: 7

bioShark
bioShark

Reputation: 703

I managed to solve my problem. It's more or less a workaround. The solution is a delete then insert method

<xmltask source="shared.xml" dest="shared.xml" outputter="simple:3">
   <remove path="/sharedobjects/connection[name/text()='MY CONNECTION']"/>
   <insert path="/sharedobjects[last()]">
      <![CDATA[
      <connection>   
         <name>MY CONNECTION</name>
      </connection>
      ]]>
   </insert>
</xmltask>

Upvotes: 2

Related Questions