Remove XML comments using Visual Studio 2010 Web Config Transformation
We are using Team Build to handle our deployments to our development server, and we have a need to remove comm开发者_开发问答ents from our web config when it's transformed. Does anyone know how to remove the <!-- -->
comment lines from the web config file using a transformation?
I've found an answer. It seems this is a known bug in the XDT transformation engine in Visual Studio/Team Build. This bug was reported in March, so no idea when this will be fixed.
Here's the link
Edit: This link actually isn't related to the original question. We eventually figured it wasn't possible with the built-in web config transformations. So we ended up writing a console application to strip comments, and properly format the transformed file.
Here is my function. You can add it to a helper class:
public static string RemoveComments(
string xmlString,
int indention,
bool preserveWhiteSpace)
{
XmlDocument xDoc = new XmlDocument();
xDoc.PreserveWhitespace = preserveWhiteSpace;
xDoc.LoadXml(xmlString);
XmlNodeList list = xDoc.SelectNodes("//comment()");
foreach (XmlNode node in list)
{
node.ParentNode.RemoveChild(node);
}
string xml;
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
if (indention > 0)
{
xtw.IndentChar = ' ';
xtw.Indentation = indention;
xtw.Formatting = System.Xml.Formatting.Indented;
}
xDoc.WriteContentTo(xtw);
xtw.Close();
sw.Close();
}
xml = sw.ToString();
}
return xml;
}
If you have small sections you want to remove comments from you might be willing to use a replace transform.
base web.config file:
<system.webServer>
<rewrite>
<rules>
<clear />
<!-- See transforming configs to see values inserted for builds -->
</rules>
</rewrite>
web.release.config transfrom (replacing contents WITHOUT comment):
<system.webServer>
<rewrite >
<rules xdt:Transform="Replace">
<clear/>
<rule name="Redirect to https" stopProcessing="true" >
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
</rules>
</rewrite>
result in final published config:
<system.webServer>
<rewrite>
<rules>
<clear />
<rule name="Redirect to https" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
</rules>
</rewrite>
You could end up copying A LOT of your config from base to the transform file using this approach but it might be appropriate in small cases...
In my case I dont want rewrite rules in my base, but I put a comment in to tell other devs to look in transforms for more info, but I dont want that comment in the final version.
精彩评论