The obvious question is: what if I want to do this in other projects that aren’t web applications, like SharePoint solutions?
Solution
Fortunately, Johan Leino has discovered a very elegant solution. You can find his solution here: http://johanleino.wordpress.com/2010/12/21/working-with-xml-transformations-in-sharepoint-part-1/. I highly recommend reading and following his example before continuing or you’re likely to get lost with my modifications.
It comes down to creating a .targets file and passing your transforms through the .targets file at compile time. The code he provides will do the actual transformation quite efficiently. However, you run into a problem using his code with Team Build automation and when you just want to package a file.
XML Transforms on Team Build 2010
To get XML transforms to work correctly in all instances, including on Team Build 2010, take the .targets file from Johan’s site and make the following change:
Where he has the line:
1: <Target Name="CopyTransformedConfigurationFiles"
2: DependsOnTargets="$(CopyTransformedConfigurationFilesDependsOn)"
3: AfterTargets="Build">
Replace this with the line:
1: <Target Name="CopyTransformedConfigurationFiles"
2: DependsOnTargets="$(CopyTransformedConfigurationFilesDependsOn)"
3: BeforeTargets="CleanPackage">
This change moves the step to happen right before the package is created instead of after the package is built and enables the transform to work on Team Build. The purpose of this is twofold:
- If you only change your XML files between builds, the files will not be transformed the second time you build.
- The way that Team Build handles the target transform file results in the incorrect file being included in the package or the file not being transformed at all.
So there you have it. A little XML and you can mimic the functionality that exists in Web Applications across any other type of XML file.