Is there any way to do a "Replace Or Insert" using web.config transformation? Is there any way to do a "Replace Or Insert" using web.config transformation? asp.net asp.net

Is there any way to do a "Replace Or Insert" using web.config transformation?


In conjunction with xdt:Transform="Remove" use xdt:Transform="InsertIfMissing" in VS2012.

<authorization xdt:Transform="Remove" /><authorization xdt:Transform="InsertIfMissing">  <deny users="?"/>  <allow users="*"/></authorization>


I found a cheap workaround. It ain't pretty and won't work very well if you have a lot of elements that needs to be "Replace Or Insert".

Do a "Remove" and then an "InsertAfter|InsertBefore".

For example,

<authorization xdt:Transform="Remove" /><authorization xdt:Transform="InsertAfter(/configuration/system.web/authentication)">  <deny users="?"/>  <allow users="*"/></authorization>


Use the InsertIfMissing transformation to ensure that the appSetting exists.
Then use the Replace transformation to set its value.

<appSettings>  <add key="Environment" xdt:Transform="InsertIfMissing" xdt:Locator="Match(key)" />  <add key="Environment" value="Live" xdt:Transform="Replace" xdt:Locator="Match(key)" /></appSettings>

You could also use the SetAttributes transformation instead of Replace. The difference is that SetAttributes does not touch child nodes.

<appSettings>    <add key="UseLivePaymentService" xdt:Transform="InsertIfMissing" xdt:Locator="Match(key)" />  <add key="UseLivePaymentService" value="true" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /></appSettings>

These techniques are much better than remove+insert because existing nodes are not moved to the bottom of their parent node. New nodes are appended at the end. Existing nodes stay where they are in the source file.

This answer applies only to newer versions of Visual Studio (2012 or newer).