2012-06-14 72 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配置的值替換。那很簡單!

相關問題