Search code examples
xpathnantxmlpoke

xmlpoke in Nant - how to update all instances of found string


Hi I am using Xpath in my Nant build script to change some config variables between development and my other environments.

I have taken the syntax from this example:

The example looks like this:

<xmlpoke
    file="config01/app.config"
    xpath="/configuration/appSettings/add[@key='AppName']/@value"
    value="TradeMonster">
</xmlpoke>

What I would like is something similar to this to search my connection strings and find all instances of "localhost\SqlExpress" and just change them to just "localhost"

Is this possible?


Solution

  • Toying with a quick'n dirty script here....

    If you're sure there is only one connectionstring element in each file you can accomplish this with a combination of xmlpeek and xmlpoke. Modifying the string is easier done with some C#, therefore using a script task to do a regex search and replace:

     <script language="C#" prefix="custom" >
          <code>
            <![CDATA[
              [Function("fix")]
              public static string Fix(string input) {
                  return Regex.Replace(input, @"localhost\\\w+", "localhost");
              }
            ]]>
          </code>
      </script>
    
    <!-- Get the existing connection string -->
    <xmlpeek
        file="config01/app.config"
        xpath="/configuration/connectionStrings/add[@contains(@connectionString,'localhost\')]/@connectionString"
        property="connectionstring">
    </xmlpeek>
    
    <!-- Write back the modified connection string -->
    <xmlpoke
        file="config01/app.config"
        xpath="/configuration/connectionStrings/add[@contains(@connectionString,'localhost\')]/@connectionString"
        value="${custom::fix(connectionstring)}">
    </xmlpoke>