Use NAnt to replace values in other xml config files

NAnt looks like a nice deployment and configuration tool. You can put important parameters in the build file and/or pass values via command line to overwrite values inside the build file, do file copy, compile code, log progress, and all kinds of stuff. This gives you great flexibility in your build and config process. But what if you need to change a setting in other related xml config file? For instance, sometimes you need to change a virtual folder name, web or database server name, or database user name that are defined in a different file.

In that case, we can use xmlpoke. Here is a sample of it:

Build file sample

<project name="HaidongProject" default="MyTarget">
	<target name="MyTarget">
		<xmlpoke file="App.config"
    		xpath="/configuration/appSettings/add[@key = 'server']/@value"
    		value="NewDatabaseServer" />
    	</target>
</project>

Config file sample

< ?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appsettings>
    <add key="server" value="OldDatabaseServer" />
  </appsettings>
</configuration>

Run

nant.exe -buildfile:build.xml

And it will change the server name in the App.config file.

By the way, today I used Windows findstr, which, like grep, supports regular expressions.

C:\Program Files\NAnt\doc\help>findstr /s /i /m xmlpoke *.*
tasks\index.html
tasks\xmlpoke.html

C:\Program Files\NAnt\doc\help>findstr /s /i /m xmlpeek *.*
fundamentals\listeners.html
tasks\index.html
tasks\xmlpeek.html

Leave a Comment