项目构建:Web.config 转换





5.00/5 (2投票s)
Web.Config XML 转换
引言
我们将学习:在项目构建期间使用 VS2010 的 TransformXml
进行转换来替换 Web.config 值,从诸如 Web.Debug.Config 和 Web.Release.Config 等配置文件中在调试或发布模式下进行转换,以及使用诸如 SlowCheetah 等工具预览转换。您可以使用 VS2010 的扩展管理器下载 SlowCheetah。
背景
Web.Config 转换语法位于 此处,基本上这是一个简单的转换示例。
Web.Debug.Config
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="ConnectionString" xdt:Locator="Match(key)" xdt:Transform="RemoveAll"/>
<add key="ConnectionString"
value="SERVER=DEBUG_SERVER;UID=TESTUSER;PWD=TESTPASSWORD;"
xdt:Transform="Insert"/>
</appSettings>
</configuration>
Web.Release.Config
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="ConnectionString" xdt:Locator="Match(key)" xdt:Transform="RemoveAll"/>
<add key="ConnectionString"
value="SERVER=PROD_SERVER;UID=PRODUSER;PWD=PRODPASSWORD;"
xdt:Transform="Insert"/>
</appSettings>
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)">
</compilation>
</system.web>
</configuration>
使用代码
最好使用 xdt:Locator="Match(key)" xdt:Transform="RemoveAll"
删除所有现有值,然后使用 xdt:Transform="Insert"
,这将确保删除所有现有值并插入新的值。
使用记事本编辑项目文件,将以下标签添加到项目文件中。这些标签:<UsingTask>
、<BeforeCompile>
和 <BeforeBuild>
用于生成转换文件。转换程序集 Microsoft.Web.Publishing.Tasks.dll 执行实际的 XML 转换。
在构建过程中(Ctrl+Shift+B),ApplyTransform 任务在编译开始之前执行,这将创建一个输出文件“Web.Config_output”,在构建过程开始之前,输出将被重命名为“Web.Config”,因此这将是在运行时使用的 Web.Config。
MyProject.csproj
<Project ToolsVersion="4.0" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...
<UsingTask TaskName="TransformXml"
AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
<Target Name="ApplyTransform" Condition="Exists('Web.$(Configuration).config')">
<TransformXml Source="web.config"
Transform="web.$(Configuration).Config" Destination="web.config_output" />
</Target>
<Target Name="BeforeCompile">
<CallTarget Targets="ApplyTransform"/>
</Target>
<Target Name="BeforeBuild">
<Exec Command="attrib -r Web.config"/>
<Copy SourceFiles="Web.config_output" DestinationFiles="Web.config" />
</Target>
...
</Project>
关注点
不仅 Web.Config 可以转换,几乎任何 XML 文件都可以转换,只需添加带有源和目标的 TransfromXml
元素即可。
更多关于 Web.Config 转换的文章,请点击 此处。