Manually Applying XML Document Transform (XDT)

There might be situations where you might want to execute XDT of a web.config or app.config “manually” (i.e. apply the transformation in your code instead of letting not Visual Studio do the work). For example, this might be necessary when you want to examine the web.config or app.config file from within a Visual Studio extension. Fortunately, this is quite easy.

The objects that Visual Studio uses to perform the transformation reside inside the assembly Microsoft.Web.Publishing.Tasks. You can find that assembly in c:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll (“v11.0” in the path applies to Visual Studio 2012). Note that you need to have Visual Studio with the Visual Web Developer option installed; otherwise, this assembly will not be available.

Now, once you habe referenced that assembly in your project, the code to apply a transformation looks like this:

/// <summary>
/// Applies XDT to the specified input file.
/// </summary>
/// <param name="inputFile">The input file to transform.</param>
/// <param name="transformationFile">The transformation file.</param>
public static XmlDocument Apply(string inputFile, string transformationFile)
{
    var doc = new XmlDocument();
    doc.Load(inputFile);
            
    var transform = new Microsoft.Web.Publishing.Tasks.XmlTransformation(transformationFile);
    transform.Apply(doc);

    return doc;
}

Here is a minimalistic example for the input file:

<configuration>
  <appSettings></appSettings>
</configuration>

Here is a minimalistic example for the transformation file:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/>
  </appSettings>
</configuration>

And this is what the result of the transformation looks like:

<configuration>
  <appSettings>
    <add name="NewSetting" value="New Setting Value"/>
  </appSettings>
</configuration>

Freelance full-stack .NET and JS developer and architect. Located near Cologne, Germany.

Leave a Reply

Your email address will not be published. Required fields are marked *