2012-06-14 35 views
193

是否有可能以下的Web.config文件的appSettings变换:如何使用Web.config文件转型改变appSettings部分属性的值

<appSettings> 
    <add key="developmentModeUserId" value="00297022" /> 
    <add key="developmentMode" value="true" /> 
    /* other settings here that should stay */ 
</appSettings> 

弄成这个样子:

<appSettings> 
    <add key="developmentMode" value="false" /> 
    /* other settings here that should stay */ 
</appSettings> 

所以,我需要删除钥匙developmentModeUserId,我需要替换钥匙developmentMode的值。

回答

345

你想要的东西,如:

<appSettings> 
    <add key="developmentModeUserId" xdt:Transform="Remove" xdt:Locator="Match(key)"/> 
    <add key="developmentMode" value="false" xdt:Transform="SetAttributes" 
      xdt:Locator="Match(key)"/> 
</appSettings> 

更多信息,请参见http://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

+20

请注意密钥区分大小写! – Cosmin

+1

优秀的答案。我正在尝试像慢猎豹这样的第三方选项,并且无处不在 - 这很简单和完美。 – Steve

+2

@stevens:如果你想为本地应用程序转换app.config文件,你需要使用Slow Cheetah。但是,如果我记得(从我必须使用Slow Cheetah开始已经有一段时间了),语法应该是相同的。 – Ellesedil

0

更换所有的AppSettings

This is the overkill case where you just want to replace an entire section of the web.config. In this case I will replace all AppSettings in the web.config will new settings in web.release.config. This is my baseline web.config appSettings: 


<appSettings> 
    <add key="KeyA" value="ValA"/> 
    <add key="KeyB" value="ValB"/> 
</appSettings> 

Now in my web.release.config file, I am going to create a appSettings section except I will include the attribute xdt:Transform=”Replace” since I want to just replace the entire element. I did not have to use xdt:Locator because there is nothing to locate – I just want to wipe the slate clean and replace everything. 


<appSettings xdt:Transform="Replace"> 
    <add key="ProdKeyA" value="ProdValA"/> 
    <add key="ProdKeyB" value="ProdValB"/> 
    <add key="ProdKeyC" value="ProdValC"/> 
</appSettings> 



Note that in the web.release.config file my appSettings section has three keys instead of two, and the keys aren’t even the same. Now let’s look at the generated web.config file what happens when we publish: 


<appSettings> 
    <add key="ProdKeyA" value="ProdValA"/> 
    <add key="ProdKeyB" value="ProdValB"/> 
    <add key="ProdKeyC" value="ProdValC"/> 
</appSettings> 

正如我们的预期 - 在web.config的appSettings完全由web.release配置的值替换。那很简单!

相关问题