Web Config Transforms: Insert If Not Exists

João Bragança picture João Bragança · Feb 27, 2013 · Viewed 27.4k times · Source

I would like to apply a transformation if and only if a matched element does not exist in the target. Trying various xpath expressions using http://webconfigtransformationtester.apphb.com/ but no luck so far.

E.g. if the target web.config looks like this:

<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
</configuration>

then the output should look like this:

<configuration>
  <connectionStrings>
    <add name="MyCs" provider="System.Data.SqlClient" connectionString="" />
    <add name="SomeOtherCs" provider="System.Data.SqlClient" connectionString="" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" />
  </system.web>
</configuration>

But if the target looks like this:

<configuration>
  <connectionStrings>
    <add name="MyCs" provider="System.Data.IChangedIt" connectionString="my connection string here" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" />
  </system.web>
</configuration>

then the result of the transformation should look like this:

<configuration>
  <connectionStrings>
    <add name="MyCs" provider="System.Data.IChangedIt" connectionString="my connection string here" />
    <add name="SomeOtherCs" provider="System.Data.SqlClient" connectionString="" />   
  </connectionStrings>
  <system.web>
    <compilation debug="true" />
  </system.web>
</configuration>

In other words, I just want to add the named connection string to configuration but let the administrator fill it in with his own values. I thought it would as simple as xdt:Transform="Insert" xdt:Locator="XPath(count(/configuration/connectionStrings)=0)" (to add a cs config section if none existed) but apparently not.

Answer

ADW334034 picture ADW334034 · May 21, 2013

Use xdt:Transform="InsertIfMissing" with the XmlTransform task in VS2012. It doesn't look like Microsoft has updated their documentation to reflect this yet.