5

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?

Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
Remotec
  • 10,304
  • 25
  • 105
  • 147

2 Answers2

4

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>
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
0

XPath only selects nodes, it cannot change nodes.

One way to accomplish the needed changes is to perform an XSLT transformation on the XML document.

In order to make this happen, you have to provide the XML document and to specify exactly which of its text nodes are to be changed.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • XPath only selects nodes, but xmlpoke (the NAnt function) changes the node selected by XPath. Xmlpoke is what the question is about. – azheglov Oct 21 '11 at 16:23
  • @azheglov: THis question is tagged "xpath". Even the phraze "I am using XPath to change ..." is incorrect. The OP wants XPath expressions "to search my connection strings" but he doesn't provide the XML document on which the XPath expressions are to be applied -- therefore this is an incomplete question. This is all I have expressed in my answer. – Dimitre Novatchev Oct 21 '11 at 17:03