Search code examples
antant-contribxmltask

Ant task to check that xml node exists in xml file


I have xml file inside that I want to add xml say

<car name="BMW">
   <color>Red</color>
   <model>x3</model>
   </car>

I wish to check if node already exists then I want to update this otheriwse wanted to add new.

I am very new to ant xmltask so my question might be very simple.

With regards, Avinash Nigam


Solution

  • using an additional root tag <foo></foo> for your example (needed for insert operation),
    with xmltask you may use =

    <!-- edit file in place, use other dest if you need to create a new file -->
    <xmltask source="path/to/file.xml" dest="path/to/file.xml">
    <!-- create property if car node with name='BMW' exists -->
    <copy path="//car[@name='BMW']/text()" property="modelexists"/>
    <!-- insert new car node if car node with name='BMW' doesn't exist -->
    <insert path="/foo" unless="modelexists">
     <![CDATA[
     <car name="BMW">
      <color>Red</color>
      <model>x3</model>
     </car>
     ]]>
    </insert>
    <!-- replace car node if car node with name='BMW' exists -->
    <replace path="//car[@name='BMW']" if="modelexists">
     <![CDATA[
     <car name="BMW">
      <color>Blue</color>
      <model>x4</model>
     </car>
     ]]>
    </replace>
    </xmltask>