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>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s