Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace property in a xml file using ANT

Tags:

replace

ant

I'm trying to replace a version number in a build.xml file using an ANT script.

I've tried various approaches, searched and re-searched StackOverflow for answers but could not get the exact query.

so here is my xml file:

<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>

<project name="feature" default="main" basedir=".">
<target name="init">    
    <property name="Version" value="1.0.0.20120327"/>
</target>

    <target name="main" depends="init">
    <description>Main target</description>
</target>
</project>

Now as u can see the Version has yesterday's date. I need to replace it with the current date.

Here is what I've tried:

<target name="replace">
    <tstamp >
    <format property="touch.time" pattern="yyyyMMdd"/>  
    </tstamp>   

<property name="Feature.dir" location="../feature" />

<!--Didnt Work-->       
 <copy file="${Feature.dir}\build.xml" tofile="${Feature.dir}\build1.xml"
filtering="yes" overwrite="yes">
<filterset>
    <filter token="Version" value="1.0.0.${touch.time}"/>
</filterset>
  </copy>

  <!--Didnt work

   <replacetoken><![CDATA[<property name="Version" value=""/>]]>  
   </replacetoken>  
   <replacevalue><![CDATA[<property name="Version"value="1.0.0.${touchtime}" />]]>
   </replacevalue>

   -->  


<!-- Didnt work 
    <copy file="${Feature.dir}/build.xml" tofile="${Feature.dir}/build1.xml" >
        <filterchain>
        <tokenfilter>
                <replaceregex pattern="^[ \t]*Version[ \t]*=.*$"
                              replace="Version=1.0.0.${touch.time}"/>
        </tokenfilter>
            </filterchain>
</copy>
-->
</target>
like image 703
sloggers1894 Avatar asked Mar 29 '12 01:03

sloggers1894


1 Answers

I would use replaceregex inside a filterchain.

For example:

<copy file="${Feature.dir}\build.xml" tofile="${Feature.dir}\build1.xml"       
    filtering="yes" overwrite="yes">
    <filterchain>
        <tokenfilter>
            <replaceregex pattern="1.0.0.[0-9.]*" replace="1.0.0.${touch.time}"/>
        </tokenfilter>
    </filterchain>
</copy>

If you want to replace the file, feel free to copy to a temp file and move it back.

<tempfile property="build.temp.file.name"/>
<copy file="${Feature.dir}\build.xml" tofile="${build.temp.file.name}" ... />
<move file="${build.temp.file.name}" tofile="${Feature.dir}\build.xml" />
like image 81
Synesso Avatar answered Nov 15 '22 08:11

Synesso