您可以使用“XML-Document-Transform 语法” 通常,此语法适用于 Web 项目,但您可以对其进行调整以用于所有类型的项目。
您必须通过添加/更新 TransformXml 任务来修改您的项目文件(例如 .csproj)。在下面的示例中,在编译期间通过在 App.config 上应用转换来执行转换。如您所见,任务引用$(Configuration)变量,因此转换命令存储在例如 App.DEBUG.config 或 App.RELEASE.config 中。您可以将其更改为您喜欢的任何 msbuild 变量。如果我没记错的话,它是$(COMPUTERNAME),所以您必须将转换放入 App.MyMachineName.config。
<UsingTask TaskName="TransformXml"
AssemblyFile="C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
<Target Name="AfterBuild">
<!-- use App.$(COMPUTERNAME).config for specific machine configuration -->
<TransformXml Source="App.config"
Condition="Exists('App.$(Configuration).config')"
Transform="App.$(Configuration).config"
Destination="$(OutDir)$(AssemblyName).dll.config"/>
</Target>
完整的描述可在德语博客上找到。
这就是您机器特定配置的样子:
<?xml version="1.0"?>
<!-- "App.MyMachineName.config" - File name corresponds to the transformation task -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="MyDbConnection"
connectionString="Data Source=MyServer;Initial Catalog=MyDb;"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>
或者,您可以使用XSL 语法