xmltask (ANT) :: replace withtext not working for null value of xml element

549 views Asked by At

I am trying to replace xml field value using xmltask ( ANT script ) . But it is not replacing the value if the xml element is empty.

for example :

   <Mydoc>
      <doc>
      <docname>abc.txt</docname>
      <doclocation>xyz</doclocation>
      </doc>
      <doc>
      <docname>mmm.txt</docname>
      <doclocation></doclocation>
      </doc>
    </Mydoc>

in the above example i want to update the "doclocation" element if "docname" element is "mmm.txt"

Script used to achieve it.

        <xmltask dest="sample.xml">
         <fileset file="sample.xml"/>

            <replace 
            path="/Mydoc/doc[docname="mmm.txt"]/doclocation/text()"
            withText="newURL"/>

          </xmltask>

the above piece of code is not working if 'doclocation' element has null/no value.

what needs to be done here to handle the null values and replace it with the new value ?

1

There are 1 answers

4
Patrice M. On

You can replace the doclocation element entirely for all cases, using a CDATA section, e.g.:

     <property name="newURL" value="https://www.stackoverflow.com"/>
     <xmltask source="sample.xml" dest="result.xml">
        <replace path="/Mydoc/doc[docname='mmm.txt']/doclocation">
           <![CDATA[ <doclocation>${newURL}</doclocation> ]]>
        </replace>
     </xmltask>