非web项目中使用XDT的实例(续)

时间:2023-03-09 20:44:12
非web项目中使用XDT的实例(续)

简化

上个实例中,我们是引用了target文件来遍历项目中的xdt项。

当项目比较小,我们又只需要针对固定的config文件进行更替时,可以使用更简化的方法

不进行项目配置文件中的插入<Import Project="$(MSBuildExtensionsPath)\Custom\TransformFiles.targets" />

而直接写入代码

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterCompile" Condition="Exists('app.$(Configuration).config')">
<!--Generate transformed app config in the intermediate directory-->
<TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
<!--Force build process to use the transformed configuration file from now on.-->
<ItemGroup>
<AppConfigWithTargetPath Remove="app.config" />
<AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
<TargetPath>$(TargetFileName).config</TargetPath>
</AppConfigWithTargetPath>
</ItemGroup>
</Target>

项目运行时会自动替换Source="app.config"的文件为Transform="app.$(Configuration).config"

排错

当进行xdt时,最常见的几个问题

1. 在xml中xdt无法识别:

排错:请确认在xml头部引入了xmlns

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

2. 系统提示无法找到XXX.dll。

排错:首先请确认安装了MSbuild,其次请查看是否已经在配置中把版本号改成了正确的配置

3. 编译没有问题,但一运行就报错

排错:很可能是初始化的问题,请检查xml格式。 xml格式的要求很严格,尽量不要手写,有时候一个空格就会导致类似的问题。