web.config transform - delete comments from connectionstring section

davids picture davids · Aug 9, 2014 · Viewed 6.9k times · Source

I store several different connection strings in my web.config for development and testing. All but one is commented out so I can change info as needed.

When I publish, I would like to replace everything (including comments) in the connectionStrings node with this:

<add name="myDb" connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};" providerName="System.Data.SqlClient"  />
<!--<add name="myDb" connectionString="Data Source={SERVER};Initial Catalog=ManEx;Integrated Security=True" providerName="System.Data.SqlClient" />-->

I know how to change the active string with this:

<add name="myDb"
     connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};"
     providerName="System.Data.SqlClient"
     xdt:Transform="Add" 
     xdt:Locator="Match(name)"/>

But I don't know how to clear out the comments I don't want and add the comment I do want.

Any ideas?

Answer

user2639740 picture user2639740 · Dec 10, 2014

Instead of transforming the string, or using "Remove" and "Insert" clean the section try using "Replace".

For example:

<connectionStrings xdt:Transform="Replace">

    <add name="myDb"
         connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};"
         providerName="System.Data.SqlClient" />

</connectionStrings>

You can configure this section exactly how you want it, even if that means you add new comments.