有没有办法使用web.config转换做“replace或插入”?
我正在使用web.config转换,如下面的post所述,以便为不同的环境生成configuration。
http://vishaljoshi.blogspot.com/2009/03/web-deployment-webconfig-transformation_23.html
我可以通过匹配键来进行“replace”转换,例如
<add key="Environment" value="Live" xdt:Transform="Replace" xdt:Locator="Match(key)" /> 我可以做“插入”,例如
 <add key="UseLivePaymentService" value="true" xdt:Transform="Insert" /> 
但是我真正觉得有用的是一个ReplaceOrInsert转换,因为我不能总是依赖于原来的configuration文件有/没有一定的关键。
有没有办法做到这一点?
我发现了一个便宜的解决方法。 如果你有很多元素需要被“replace或插入”,那么这不是很好,并且不能很好地工作。
做一个“删除”,然后是“InsertAfter | InsertBefore”。
例如,
 <authorization xdt:Transform="Remove" /> <authorization xdt:Transform="InsertAfter(/configuration/system.web/authentication)"> <deny users="?"/> <allow users="*"/> </authorization> 
 结合xdt:Transform="Remove" xdt:Transform="InsertIfMissing"在VS2012中使用xdt:Transform="InsertIfMissing" 。 
 <authorization xdt:Transform="Remove" /> <authorization xdt:Transform="InsertIfMissing"> <deny users="?"/> <allow users="*"/> </authorization> 
 使用InsertIfMissing转换来确保appSetting存在。 
 然后使用Replace转换来设置其值。 
 <appSettings> <add key="Environment" xdt:Transform="InsertIfMissing" xdt:Locator="Match(key)" /> <add key="Environment" value="Live" xdt:Transform="Replace" xdt:Locator="Match(key)" /> </appSettings> 
 您也可以使用SetAttributes转换而不是Replace 。 不同的是SetAttributes不会触及子节点。 
 <appSettings> <add key="UseLivePaymentService" xdt:Transform="InsertIfMissing" xdt:Locator="Match(key)" /> <add key="UseLivePaymentService" value="true" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /> </appSettings> 
这些技术比删除+插入要好得多,因为现有节点不会移动到其父节点的底部。 最后附加新节点。 现有节点保留在源文件中的位置。
这个答案只适用于较新版本的Visual Studio(2012或更新版本)。
对我来说更好的方法是只有当元素不存在时才插入元素,因为我只设置了某些属性。 删除元素会丢弃主元素的任何其他属性(如果存在)。
例如:web.config(没有元素)
 <serviceBehaviors> <behavior name="Wcf.ServiceImplementation.AllDigitalService_Behavior"> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> 
web.config(带元素)
 <serviceBehaviors> <behavior name="Wcf.ServiceImplementation.AllDigitalService_Behavior"> <serviceDebug httpsHelpPageEnabled="true" /> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> 
使用带有XPathexpression式的定位器,如果节点不存在,则添加该节点,然后设置我的属性:
 <serviceDebug xdt:Transform="Insert" xdt:Locator="XPath(/configuration/system.serviceModel/behaviors/serviceBehaviors/behavior[not(serviceDebug)])" /> <serviceDebug includeExceptionDetailInFaults="true" xdt:Transform="SetAttributes" /> 
所产生的web.config文件都有includeExceptionDetailInFaults =“true”,第二个保留了httpsHelpPageEnabled属性,其中remove / insert方法不会。
下面创build一个新的密钥是相同的密钥不存在。 如果存在的话,它只是取代现有的。
 <add key="some key" xdt:Transform="InsertIfMissing" xdt:Locator="Match(key)"/> <add key="some key" value="some value" xdt:Transform="Replace" xdt:Locator="Match(key)" />