2

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 ?

nikhil
  • 21
  • 2

1 Answers1

1

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>
Patrice M.
  • 4,209
  • 2
  • 27
  • 36
  • Is there any way to replace the text , if the text does not exists ?? – nikhil Jul 10 '17 at 06:10
  • This code should work for or . Is that what you're asking ? – Patrice M. Jul 10 '17 at 14:21
  • yes , it should be able to insert text in the element or without replacing the whole element with Cdata tag , is it possible ? – nikhil Jul 11 '17 at 07:01
  • My solution replaces the whole element, and I trust you have tried it. Can you explain under which circumstances it would be a problem to replace the whole element as opposed to 'just' the content ? – Patrice M. Jul 11 '17 at 13:33